Evaluating the string in a variable to use as a method name

  • Thread starter heinous (sent by Nabble.com)
  • Start date
H

heinous (sent by Nabble.com)

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?([email protected]_s)
@tmphash[[email protected]_s] = Array.new
end
@tmphash[[email protected]_s].push(object)
end
end

Where the method name is the @attr value.
 
R

Robert Klemme

heinous (sent by Nabble.com) said:
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?([email protected]_s)
@tmphash[[email protected]_s] = Array.new
end
@tmphash[[email protected]_s].push(object)
end
end

You cannot use @attr, @attr is reserved for instance variables. Also, it's
a bad idea to use instance variables (@tmparray, @tmphash) as temporary
variables.
Where the method name is the @attr value.

It's a one liner:

objects.sort_by {|o| o.send(attr)}

Kind regards

robert
 
H

heinous (sent by Nabble.com)

You cannot use @attr, @attr is reserved for instance variables. Also, it's
a bad idea to use instance variables (@tmparray, @tmphash) as temporary
variables.

Gotcha there, I wasn't planning to, it was more to make the variable more
obvious in the example.
It's a one liner:
objects.sort_by {|o| o.send(attr)}

Exactly what I needed, thanks... Now we're just looking at something like:

def sort_obj(objects,attr)
objects.sort_by {|o| o.send(attr)}
end
 
R

Robert Klemme

heinous (sent by Nabble.com) said:
Gotcha there, I wasn't planning to, it was more to make the variable more
obvious in the example.

It's generally preferred to use pieces of code that are syntactically
correct and do something. That makes everyone's lives easier. :)
Exactly what I needed, thanks... Now we're just looking at something
like:

def sort_obj(objects,attr)
objects.sort_by {|o| o.send(attr)}
end

Not really worth a method IMHO bur YMMV.

Kind regards

robert
 

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,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top