Forum: Ruby on Rails Calling method through variable

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.
Daniel P. (Guest)
on 2007-01-19 15:44
I have a  variable and I want to call a method with the name of the
variable
example:
method_variable = "sum"

def sum
 ....
end

How can i do that?

thank...
Alan F. (Guest)
on 2007-01-19 16:18
Daniel Pérez wrote:
> I have a  variable and I want to call a method with the name of the
> variable
> example:
> method_variable = "sum"
>
> def sum
>  ....
> end
>
> How can i do that?
>
> thank...

self.send(method_variable)

Alan
Chris H. (Guest)
on 2007-01-19 16:24
(Received via mailing list)
use the Object.send instance method

class Klass
  def sum(a, b)
     a + b
  end
end

k = Klass.new
m = "sum"

k.send m.to_sym, 1, 2
=> 3


Chris
This topic is locked and can not be replied to.