开发者

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

开发者 https://www.devze.com 2022-12-21 20:33 出处:网络
it\'s about Ruby. I\'ve got a Box Object with attributes such as \"panel1\", \"panel2\", ..., \"panel5\".

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 correc开发者_如何学Ct way?

Yours, Joern.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号