Steve Hull wrote:
> Hey ruby wizards.  I got a question for you.  I want to call a method on
> my object instance, with the method name specified by a string.  I want
> to *pass in* a hash to my method.
> 
> I tried:
> 
> myMethodName = "doSomeStuff"
> myObject.instance_eval "#{myMethodName}(#{myHash})"
> 
> But it complained that it didn't have a method named #{myHash.to_s}.

You can easily see what you've done wrong if you just use 'puts' instead 
of 'myObject.instance_eval'

Here's it's because you turned the hash into a string, and then inserted 
the string into your code, and then tried to run it.

irb(main):001:0> myHash={"one"=>1}
=> {"one"=>1}
irb(main):002:0> def showit(x); puts "got #{x.inspect}"; end
=> nil
irb(main):003:0> myMethodName = "showit"
=> "showit"
irb(main):004:0> puts "#{myMethodName}(#{myHash})"
showit(one1)
=> nil

Imagine what happens if you type "showit(one1)" at the command line.

What you needed was just to pass literally 'myHash' as the argument, 
whilst still interpolating the method name, i.e.

irb(main):005:0> instance_eval "#{myMethodName}(myHash)"
got {"one"=>1}
=> nil

However there are better ways to achieve this, without using the string 
version of eval. Probably all you want is this:

    myObject.send(myMethodName, myHash)

> I'm new to metaprogramming in ruby.  What am I missing here?

This isn't metaprogramming (metaprogramming = programs which write 
programs). This is just dynamic method dispatch.

Regards,

Brian.
-- 
Posted via http://www.ruby-forum.com/.