tags:

views:

53

answers:

2

Hi folks,

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.

+3  A: 

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.

bojo
thanks, you solve the problem completely! :)
Joern Akkermann
I just tweaked it a little to add parameters. Glad I could help.
bojo
Using send instead of eval is definitely the preferred way
Beerlington
+4  A: 

You're almost there. You just need to replace "method_call" with "send", which is how methods are actually called in Ruby - messages are sent to objects.

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
Mike Woodhouse