How can I call a ruby ​​object method by specifying a string as the method name

This is about Ruby.

I have a Box object with attributes like "panel1", "panel2", ..., "panel5". Instead of calling Box.panel1, Box.panel2, ... I want to name it as Box.method_call ("panel" + some_integer.to_s).

I am sure there is such a way, but how is it right?

Regards, Jorn.

+3
source share
2 answers

Given:

class Box
   def self.foo
      puts "foo called"
   end
   def self.bar(baz)
      puts "bar called with %s" % baz
   end
end

You can use eval :

eval("Box.%s" % 'foo')
eval("Box.%s('%s')" % ['bar', 'baz'])

Using send is probably more preferable:

Box.send 'foo'
Box.send 'bar', 'baz'

Hope this helps.

+5
source

. "method_call" "send", Ruby - .

class Box
  def panel1
    puts 1
  end
  def panel2
    puts 2
  end
end

box = Box.new #=> #<Box:0x2e10634>
box.send("panel1")
1
panel = 2
box.send("panel#{panel}")
2
+5

Source: https://habr.com/ru/post/1735553/


All Articles