how do I call a method of an ruby object by giving a string as the method name

methods, ruby

Solution

Given:

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

You could use eval:

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

Using send probably more preferred:

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

Hope that helps.

Problem

it's about Ruby. I've got a Box Object with attributes such as "panel1", "panel2", ..., "panel5". Instead of calling Box.panel1, Box.panel2, ... I want to call it like Box.method_call("panel" + some_integer.to_s). I'm sure there is a way like this, but how's the correct way? Yours, Joern.

Original source