2

Full code: 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!"

This returns:

:foo
#===---
:foo
:foo=

Because it is treating foo = "" as a local variable within instance_eval, it's not recognize it as a method.

How would I make instance_eval treat it as a method?

3
  • what do you want 'options.foo="it aint . . . "' to do? Commented Dec 16, 2009 at 21:57
  • To be captured within method_missing for me to manipulate it, specifically to set a key/value in a hash. It'll kinda work like a Struct. Commented Dec 16, 2009 at 22:00
  • Check out the full code (link at the top of post) Commented Dec 16, 2009 at 22:01

2 Answers 2

5

The expression foo = "" will never be a method call. It is a local variable assignment. This is a fact of Ruby's syntax. In order to call a setter, you have to specify a receiver explicitly. This is why most Ruby pseudo-DSLs use the Dwemthy-style:

class Dragon < Creature
  life 1340     # tough scales
  strength 451  # bristling veins
  charisma 1020 # toothy smile
  weapon 939    # fire breath
end

That avoids the equals sign problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh geez, why didn't I think of this? Thats perfect =D
2

Do self.foo = "" to make it treat it as a method.

4 Comments

Yeah, that would work I suppose. But the reason I'm trying to figure this out is so I don't have to use self.foo or options.tap { |o| o.foo } to run methods =/
Here is my full code, if you are intersted: friendpaste.com/5TdtGPZaEK0DbDBa2DCUyB
Sadly, I don't think it is possible. foo = will always be interpreted as a local variable assignment and there is no way of getting to local variables defined inside a block.
It seems even foo=() will not work. Oh well, I guess I will have to do it your way. Thanks

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.