为什么 Ruby 2.0 改进后“发送"会失败? [英] Why does `send` fail with Ruby 2.0 refinement?
本文介绍了为什么 Ruby 2.0 改进后“发送"会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这不起作用?
module StringRefinement
refine String do
def bar
length
end
end
end
using StringRefinement
"abcdefghijklmnopqrstuvwxyz".send(:bar)
#NoMethodError: undefined method 'bar' for "abcdefghijklmnopqrstuvwxyz":String
有人可以解释为什么 send
在这里不起作用吗?有没有办法动态调用细化中定义的方法?我似乎找不到关于 Ruby 2.0 中细化如何工作的完整解释.
Can someone explain why send
doesn't work here? And is there a way to dynamically call methods defined in a refinement? I can't seem to find a good, full explanation of how refinements work in Ruby 2.0.
推荐答案
因为规范 是这样说的:
任何间接方法访问,例如 Kernel#send
、Kernel#method
和 Kernel#respond_to?
都不应支持调用者中的改进方法查找期间的上下文.
Indirect method accesses
Any indirect method access such as
Kernel#send
,Kernel#method
, andKernel#respond_to?
shall not honor refinements in the caller context during method lookup.
这篇关于为什么 Ruby 2.0 改进后“发送"会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文