在Ruby中按名称访问类型

时间:2013-01-19 09:39:52

标签: ruby

在红宝石中,我可以说(我只选择了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

我该怎么做?如何通过名称访问类型来调用其方法?

1 个答案:

答案 0 :(得分:2)

type是一个字符串,例如。 'MyItem1'或'MyItem2'?

尝试Object.const_get(type).method123(arg1, arg2)