Ruby Instance Eval

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

Why does the 'set' method fail?

EDIT

Figured it out…

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

Needed to be:

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

Best Answer

Yep - yield evaluates in the context within which it was defined.

Good write up here, but a simple example shows the problem:

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