0

ルビーで言えば(たとえば、Mongoidを取り上げただけです)

class MyItem
  include Mongoid::Document
  include Mongoid::Timestamps

  #.................

  def method1(some_type)
    raise "Not symbol" unless some_type.is_a?(Symbol)
    raise "Unsupported some_type (#{some_type})" unless [:some_type1, :some_type2, :some_type3].include?(some_type)
    min_time_to_update = 60*60
    full_method_name = "#{some_type}_another_method".to_sym()

    !!self.send(full_method_name)
  end
end

そしてそれを呼び出します

result = MyItem.first.method1(:some_type2)

ここでは、メソッドsendを使用して、型のメソッドをその名前で呼び出しています。しかし、次のことをしたい場合はどうすればよいですか

  def method1(type, arg1, arg2)
     #check if it's a correct type....
     # type might be either MyItem1 or MyItem2 or anything that has a method `method123`
     "#{type}".method123(arg1, arg2)
  end

どうやってやるの?そのメソッドを呼び出すために、その名前で型にアクセスするにはどうすればよいですか?

4

1 に答える 1

2

type文字列であること。「MyItem1」または「MyItem2」?

試してみてくださいObject.const_get(type).method123(arg1, arg2)

于 2013-01-19T09:42:45.610 に答える