2

Is it possible to use a string to call a method on an object. For instance with a string foo = 'bar', how could I call bar on the class Baz: Baz.bar. An alternative would be to create a case statement like this;

case foo
when 'bar'
  Baz.bar
when 'qux'
  Baz.qux
end
Gregology
  • 1,625
  • 2
  • 18
  • 32
  • Hi @mu-is-too-short, I was googling for a while to find a solution and the suggested duplicate never came up. I assume it never came up because it's referring to methods as functions. I appreciate that the answer is the same but hopefully this question will save a dev some time in the future. Either that or update the duplicate question to use the term "method" instead, especially in the title so it comes up on searches. – Gregology Feb 22 '19 at 16:07

1 Answers1

4

You can call just any method on an object with send:

foo = 'bar'
Baz.send(foo) // calls bar on Baz

This calls private methods, too. If you only want to call public methods use public_send:

foo = 'bar'
Baz.public_send(foo) // calls only public method bar on Baz

If you want to check if a public method is defined, you can use respond_to?

foo = 'bar'
if Baz.respond_to?(foo)
  // only gets executed if public method bar is defined on Baz
  Baz.send(foo) // executes bar on Baz
end

If you want to also check private methods you have to provide true as second arg:

Baz.respond_to?(foo, true)
mbuechmann
  • 5,413
  • 5
  • 27
  • 40