Ruby Instance_eval

时间:2009-12-16 20:09:29

标签: ruby

class Setter
    attr_accessor :foo

    def initialize
        @foo = "It aint easy being cheesy!"
    end

    def set
        self.instance_eval { yield if block_given? }
    end
end

options = Setter.new

# Works
options.instance_eval do
    p foo
end

# Fails
options.set do
    p foo
end

为什么'set'方法会失败?

修改

想出来......

def set
    self.instance_eval { yield if block_given? }
end

需要:

def set(&blk)
    instance_eval(&blk)
end

1 个答案:

答案 0 :(得分:2)

是的 - 产量在其定义的上下文中进行评估。

好写here,但是一个简单的例子显示了问题:

>> foo = "wrong foo"
>> options.set do
?>     p foo
>> end
"wrong foo"