help - calling methods in a hash with parameters

T

Tuan Bui

Hiya,

If I want to create a hash table with the values containing methods to
call, how do i call these methods if they need parameters? Here's an
example:

irb(main):001:0> def methodone
irb(main):002:1> puts "hi, i am method one"
irb(main):003:1> end
=> nil
irb(main):004:0> def methodtwo(input)
irb(main):005:1> puts input
irb(main):006:1> end
=> nil
irb(main):007:0> myhash = { 'foo' => 'methodone', 'bar' => 'methodtwo' }
=> {"foo"=>"methodone", "bar"=>"methodtwo"}
irb(main):008:0> eval myhash["foo"]
hi, i am method one
=> nil
irb(main):009:0> eval myhash["bar"] "hi, i am method two"
SyntaxError: compile error
(irb):9: parse error
from (irb):9
irb(main):010:0>


In other words, how do I pass a parameter to method two?

If my implementation of what I want to do looks lame, please let me know
of a better way... I am pretty new to Ruby.

Thanks!
Tuan
 
B

Brian Candler

eval myhash["bar"] + '("Thing to say")'

No, don't do that! Calling the compiler should be a last resort.

Instead, convert your method into an object reference so it can be put
straight into the hash:

myhash = {'foo' => method:)methodone), 'bar' => method:)methodtwo)}

myhash['foo'].call
myhash['bar'].call('hi, I am method two')

Check the docs for Method to find out other useful things (e.g. Method#arity
will tell you how many arguments it needs, before you call it)

Regards,

Brian.

irb(main):001:0> def methodone
irb(main):002:1> puts "hi, i am method one"
irb(main):003:1> end
=> nil
irb(main):004:0> def methodtwo(input)
irb(main):005:1> puts input
irb(main):006:1> end
=> nil
irb(main):007:0> myhash = { 'foo' => 'methodone', 'bar' => 'methodtwo'
}
=> {"foo"=>"methodone", "bar"=>"methodtwo"}
irb(main):008:0> eval myhash["foo"]
hi, i am method one
=> nil
irb(main):009:0> eval myhash["bar"] "hi, i am method two"
SyntaxError: compile error
(irb):9: parse error
from (irb):9
irb(main):010:0>


In other words, how do I pass a parameter to method two?
 
T

Tuan Bui

In case anyone wants to know of a solution, Lyle was kind enough to
email me one:

to call, how do i call these methods if they need parameters?
Here's one alternative:

myhash = { 'foo' => method('methodone'),
'bar' => method('methodtwo') }

myhash["foo"].call
myhash["bar"].call "hi, i am method two"

The method() method returns a reference to a Method object for the
named method (could I use the word "method" a few more times in that
sentence?) And call() is an instance method for Method objects.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top