Passing function names from string variables


#1

This may be a more generic Ruby question, so I’m going to ask on the
Ruby
forum, but I’m trying to figure out if there is a way to pass in the
string
value of a variable as the name of a method.

For example, I would like to do something like:

def sort_obj_by_uid(objects,@attr)
@tmparray = Array.new
@tmphash = Hash.new
for object in @objects
if ! @tmphash.has_key?(removed_email_address@domain.invalid_s)
@tmphash[removed_email_address@domain.invalid_s] = Array.new
end
@tmphash[removed_email_address@domain.invalid_s].push(object)
end
end

Where the method name is the @attr value.


#2

Hi –

On Thu, 16 Mar 2006, Leah C. wrote:

 if ! @tmphash.has_key?(removed_email_address@domain.invalid_s)
   @tmphash[removed_email_address@domain.invalid_s] = Array.new
 end
 @tmphash[removed_email_address@domain.invalid_s].push(object)

end
end

Where the method name is the @attr value.

Yes: send, like this:

object.send(@attr).to_s

If you want to send additional arguments, you put them in the second,
third… positions.

David


David A. Black (removed_email_address@domain.invalid)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

“Ruby for Rails” chapters now available
from Manning Early Access Program! http://www.manning.com/books/black


#3

Very easy:

@obj.send(@attr.to_sym)


#4

On Thu, 16 Mar 2006, removed_email_address@domain.invalid wrote:

def sort_obj_by_uid(objects,@attr)
Where the method name is the @attr value.

Yes: send, like this:

object.send(@attr).to_s

Whoops, I meant:

object.send(@attr.to_s)

David


David A. Black (removed_email_address@domain.invalid)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

“Ruby for Rails” chapters now available
from Manning Early Access Program! http://www.manning.com/books/black