3

Let's say I have a class

class MyClass
  def sayMyName()
    puts "I am unknown"
  end
end

and I have stored this method name in a variable: methodName = "saymyName"

I want to call this method by using above variable, something like this:

instance = MyClass.new
instance[methodName] 

I know it can be called using a macro but I don't get how? Please someone provide an example with explanation.

Update 1

There is already an answer for this: Calling methods dynamically (Crystal-lang) but this doesn't answer how to do it when methods are inside a class.

Ujjwal Kumar Gupta
  • 2,308
  • 1
  • 21
  • 32
  • Sadly, it looks like you can't do that: https://stackoverflow.com/a/48521707/9288880 – WPeN2Ic850EU Jan 31 '20 at 09:49
  • Its written there that we can do using macro but not how ? – Ujjwal Kumar Gupta Jan 31 '20 at 13:43
  • How to best solve it depends a lot on your application / library / specific needs. Usually you can avoid the need for something like this in the first place. As it stands the question is too general and a duplicate of the one linked by @WPeN2Ic850EU – Jonne Haß Feb 01 '20 at 18:32
  • 1
    See also [Calling methods dynamically (Crystal-lang)](https://stackoverflow.com/questions/55919678/calling-methods-dynamically-crystal-lang) – Jonne Haß Feb 01 '20 at 18:34
  • thanks Jonne, but that answer is without class, how to do it if methods are in class. – Ujjwal Kumar Gupta Feb 02 '20 at 04:42

1 Answers1

3

I have adapted the example given in the update:

class Foo
  def method1
    puts "i'm  method1"
  end

  def method2
    puts "i'm method2"
  end

  def method3
    puts "i'm  method3"
  end

  def bar
    { "ctrl":  -> { method1 },
      "shift": -> { method2 },
      "alt":   -> { method3 }
    }
  end

  def [](method)
    bar[method]
  end
end

binding = ["ctrl", "shift", "alt"].sample
foo = Foo.new
foo[binding].call #=> one of them

Working Example

Samual
  • 188
  • 1
  • 7