Forum: Ruby on Rails Passing function names from string variables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E09171ba6dbeef3d69ac8f16ae23ecd6?d=identicon&s=25 Leah Cunningham (Guest)
on 2006-03-16 18:21
(Received via mailing list)
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?(object.@attr.to_s)
        @tmphash[object.@attr.to_s] = Array.new
      end
      @tmphash[object.@attr.to_s].push(object)
    end
  end

Where the method name is the @attr value.
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-03-16 18:25
(Received via mailing list)
Hi --

On Thu, 16 Mar 2006, Leah Cunningham wrote:

>      if ! @tmphash.has_key?(object.@attr.to_s)
>        @tmphash[object.@attr.to_s] = Array.new
>      end
>      @tmphash[object.@attr.to_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 (dblack@wobblini.net)
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
573b9499030e1ccb867ef80f0ff1ac49?d=identicon&s=25 Justin Bailey (Guest)
on 2006-03-16 18:25
(Received via mailing list)
Very easy:

@obj.send(@attr.to_sym)
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2006-03-16 18:28
(Received via mailing list)
On Thu, 16 Mar 2006, dblack@wobblini.net 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 (dblack@wobblini.net)
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
This topic is locked and can not be replied to.