首页 > 解决方案 > 为什么 Module#define_method 忽略方法命名“规则”

问题描述

以下内容不能用作方法定义(除非我们为 定义单例方法the):

def the.dot
  :dot
end

但是,使用Module#define_method它可以正常工作:

define_method('the.dot') { :dot }
#=> :"the.dot"
method('the.dot')
#=> #<Method: main.the.dot>

以通常的方式调用它会引发异常:

the.dot
#=> NameError: undefined local variable or method `the' for main:Object

但是有一些方法可以调用这个方法:

method('the.dot').call
#=> :dot
public_send('the.dot')
#=> :dot

为什么define_method通过允许几乎任何东西作为方法名称来忽略方法命名规则?

标签: rubysyntax

解决方案


define_method符号作为第一个参数。如果你给它传递一个字符串,它会将该字符串转换为一个符号,在这种情况下,这看起来很奇怪,因为它:"the.dot"就像一个符号:thedot,但是 Ruby 引用它,因为否则它会破坏 ruby​​ 语法。

> "the.dot".to_sym
=> :"the.dot"
> "thedot".to_sym
=> :thedot
> "the dot".to_sym
=> :"the dot"
> define_method("the dot") { "yep, this works" }
=> :"the dot"
> method("the dot").call
=> "yep, this works"

推荐阅读