按名称调用方法

时间:2012-12-10 22:32:47

标签: ruby

有谁知道如何将方法称为字符串?例如:

case @setting.truck_identification
when "Make"
  t.make
when "VIN"
  t.VIN
when "Model"
  t.model
when "Registration"
  t.registration

.to_sym似乎不起作用。

4 个答案:

答案 0 :(得分:5)

使用.send

t.send @setting.truck_identification.downcase

vin应该是小写的,因为它可以工作)

答案 1 :(得分:2)

您将要使用Object#send,但您需要使用正确的大小写来调用它。例如:

[1,2,3].send('length')
=> 3

编辑:此外,虽然我会犹豫推荐它,因为看起来不好的做法会导致意外的错误,您可以通过搜索对象支持的方法列表来处理不同的大小写

method = [1,2,3].methods.grep(/LENGth/i).first
[1,2,3].send(method) if method
=> 3

我们使用不区分大小写的正则表达式遍历所有方法,然后将第一个返回的符号发送到对象(如果找到)。

答案 2 :(得分:1)

您可以使用Object#send方法将方法名称作为字符串传递。 例如:

t.send(@setting.truck_identification)

您可能需要使用String#downcase方法规范化truck_identification。

答案 3 :(得分:1)

通过这些方法获取并不是最干净的方法。只需使用#respond_to?()

即可
method = @setting.truck_identification.downcase
if t.respond_to?(method)
    t.send(method)
end
相关问题