Forum: Ruby Manipulating functions-runtime

Posted by Prog Rammer (proggrammer)
on 2012-08-16 15:51
suppose
var="world"
I want to call a method called hello_world() using the variable var. How
to do that in ruby?
and what feature of programing is this called?suppose
var="world"
I want to call a method called hello_world() using the variable var. How
to do that in ruby?
and what feature of programing is this called?

to be clear:
I want something like calling the method like :
hello_+$var+()
Posted by Jan E. (jacques1)
on 2012-08-16 16:44
Hi,

Dynamically calling methods can be done with send (or public_send):

def hello_world
  puts 123
end

var = 'world'
send('hello_' + var)
Posted by Robert Klemme (robert_k78)
on 2012-08-16 16:49
(Received via mailing list)
On Thu, Aug 16, 2012 at 3:51 PM, ajay paswan <lists@ruby-forum.com> 
wrote:
> to be clear:
> I want something like calling the method like :
> hello_+$var+()

You can do

send "hello_#{var}"

to dispatch to a method with a calculated name.  An alternative
approach is to do this:

my_methods = {
  'world' => lambda { puts "hello world" },
  'moon' => lambda { puts "hello moon" },
  'sun' => lambda { puts "hello sun" },
}

and then

my_methods[var].call

But in that case you'd rather use a method argument, of course:

def hello(x)
  puts "hello #{x}"
end

hello("world")

hello is a method (or rather function but Ruby does not have functions
which are not associated with a particular object).  x is the
argument.  "#{...}" is string interpolation.

Kind regards

robert
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.