Ujjwal Kumar Gupta
Ujjwal Kumar Gupta

Reputation: 2376

How do I call instance method from string?

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.

Upvotes: 3

Views: 532

Answers (1)

Samual
Samual

Reputation: 188

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

Upvotes: 3

Related Questions