完整代码:http://friendpaste.com/5TdtGPZaEK0DbDBa2DCUyB
class Options
def method_missing(method, *args, &block)
p method
end
end
options = Options.new
options.instance_eval do
foo
foo = "It aint easy being cheesy!"
end
puts "#===---"
options.foo
options.foo = "It still aint easy being cheesy!"
Run Code Online (Sandbox Code Playgroud)
返回:
:foo
#===---
:foo
:foo=
Run Code Online (Sandbox Code Playgroud)
因为它foo = ""在instance_eval中被视为局部变量,所以它不会将其视为一种方法.
我如何让instance_eval将其视为一种方法?
表达式foo = ""永远不会是方法调用.这是一个局部变量赋值.这是Ruby语法的一个事实.要调用setter,必须明确指定接收器.这就是大多数Ruby伪DSL使用Dwemthy风格的原因:
class Dragon < Creature
life 1340 # tough scales
strength 451 # bristling veins
charisma 1020 # toothy smile
weapon 939 # fire breath
end
Run Code Online (Sandbox Code Playgroud)
这避免了等号问题.
| 归档时间: |
|
| 查看次数: |
341 次 |
| 最近记录: |