Calling object method from variable

F

Frodo Larik

Hi all,

I have two questions regarding object methods

1. Is it possible to call a method from a variable?
Something like this:

i_am_just_a_var = 'this_is_the_real_method'
o = Object.new
o.#{i_am_just_a_var} = 'some thing I want'



2. What is the best way to check for a method of an object?

After playing around in irb I came up with this:

o = Object.new
if ( o.methods.grep(/^some_method_name$/ )
# do stuff
else
# do something else
end


Sincerely,

Frodo Larik
 
R

Robert Klemme

2005/8/29 said:
Hi all,
=20
I have two questions regarding object methods
=20
1. Is it possible to call a method from a variable?
Something like this:
=20
i_am_just_a_var =3D 'this_is_the_real_method'
o =3D Object.new
o.#{i_am_just_a_var} =3D 'some thing I want'

o.send("#{i_am_just_a_var}=3D", 'some thing I want')
2. What is the best way to check for a method of an object?
=20
After playing around in irb I came up with this:
=20
o =3D Object.new
if ( o.methods.grep(/^some_method_name$/ )
# do stuff
else
# do something else
end

o.respond_to? :foo
o.send:)respond_to?, i_am_just_a_var)

Cheers

robert
 
L

Lionel Thiry

Frodo Larik a écrit :
Hi all,

I have two questions regarding object methods

1. Is it possible to call a method from a variable?
Something like this:

i_am_just_a_var = 'this_is_the_real_method'
o = Object.new
o.#{i_am_just_a_var} = 'some thing I want'

var_method = YourClass.instance_method:)real_method)
o = YourClass.new
var_method.bind(o).call

or

o = YourClass.new
var_method = o.method:)real_method)
var_method.call

also

o = YourClass.new
var_method = o.method:)real_method=)
var_method.call 'some thing I want'

Please note: do not write var_method.call='some thing I want', you'll
get an error.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top