2
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

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.