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
1
  • 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, 2019 at 16:07

1 Answer 1

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)
1
  • Thank you! I was googling for ages but I didn't know what I should be searching for :+1:
    – Gregology
    Feb 20, 2019 at 15:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.