在 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
我怎样才能做到这一点?如何通过名称访问类型以调用其方法?