通过Ruby中的名称访问该类型
在ruby中,我可以说(我只选择了Mongoid作为例子) 叫它通过Ruby中的名称访问该类型,ruby,Ruby,在ruby中,我可以说(我只选择了Mongoid作为例子) 叫它 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
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
我该怎么做?如何通过名称访问类型以调用其方法?
type
是一个字符串,例如“MyItem1”或“MyItem2”
尝试
Object.const\u get(type).method123(arg1,arg2)
什么是list\u type
?什么是MyItem#first
?解释所有非标准的方法或局部变量。此外,在Ruby中,使用了“class”一词。使用“类型”使其难以立即理解,并给读者带来额外负担。
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