0

配列の要素に対して、名前を指定してメソッドを呼び出すにはどうすればよいですか?

たとえば、次のようにすることができます。

thing = "each"

私は次のようなことができるようにしたい:

def do_thing(thing)
  array = [object1,object2]
  array[0].thing
end

do_thing(to_s)たとえば、 が実行されるようにしますobject1.to_s

4

3 に答える 3

3

public_sendまたはを使用できますsend。パブリックメソッドとプライベートメソッドを見ることができpublic_sendますが、パブリックメソッドにのみ送信します。send

def do_thing(thing)
  array = [1,2,3]
  array.public_send(thing)
end

do_thing('first')
# => 1

do_thing(:last)
# => 3

より一般的なバージョンを更新します。

def do_thing(array, index, method, *args)
  array[index].public_send(method, *args)
end

do_thing([1, 2, 3], 0, :to_s)
# => "1"

do_thing([[1,2], [3, 4]], 0, :fetch, 0)
# => 1

require 'ostruct'
o = OpenStruct.new(attribute: 'foo')
do_thing([o], 0, :attribute=, 'bar')
o.attribute == 'bar'
# => true
于 2013-06-07T13:30:34.013 に答える
0

オブジェクト#send

thing = "each"
def do_thing(thing)
  array = [1,2,3]
  array.send(thing)
end

ドキュメントから:

class Klass
  def hello(*args)
    "Hello " + args.join(' ')
  end
end
k = Klass.new
k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"
于 2013-06-07T13:31:10.570 に答える