Calling object method from variable

(Frodo Larik) #1

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

(Robert K.) #2

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'

o.send("#{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

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

Cheers

robert

···

2005/8/29, Frodo Larik <lists@elasto.nl>:

(Lionel Thiry) #3

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.

···

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

--
Lionel Thiry

Personal web site: http://users.skynet.be/lthiry/