Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call instance method from string?

Tags:

crystal-lang

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.

like image 916
Ujjwal Kumar Gupta Avatar asked Sep 08 '26 18:09

Ujjwal Kumar Gupta


1 Answers

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

like image 85
Samual Avatar answered Sep 12 '26 23:09

Samual



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!