ruby - 为什么 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
通过允许几乎任何东西作为方法名称来忽略方法命名规则?
解决方案
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"
推荐阅读
- java - 在休眠中保存时出现 NullPointerException
- python - 尝试从 Django ADMIN 中的外部用户模型调用 is_active 方法
- excel - 运行时错误 1004 MDeterm 属性
- c - 如何使用 C 中的错误处理代码访问并行结构值
- angular - formsarray 中的 formarray.controls 在角度 5 中是什么意思?
- matlab - 模糊 c 均值聚类
- regex - 使用正则表达式确保某些内容包含单独的数字
- java - 使用 Jackson JsonParser 跳过字节
- python - 在 Python 中使用多个条目格式化 Dictionary 的正确方法
- python - 是否可以使用 PyPDF2 将多边形注释写入 pdf?