【发布时间】:2014-08-25 15:26:38
【问题描述】:
我正在尝试使用 Russ Olsen 在他的书 Eloquent Ruby 中公开的方法构建一个小巧的 DSL。但是它对我不起作用。让我们考虑以下代码:
class SayHello
def initialize
@message = "Hello."
instance_eval(yield) if yield
end
def say_it
puts @message
end
end
SayHello.new { say_it }
我得到的错误是:
say_hello.rb:12:in `block in <main>': undefined local variable or method `say_it' for main:Object (NameError)
from say_hello.rb:4:in `initialize'
from say_hello.rb:12:in `new'
from say_hello.rb:12:in `<main>'
但是……当你使用instance_eval方法时,self的值不应该分配给调用该方法的对象吗?
提前致谢!
【问题讨论】:
标签: ruby