2012-12-10 130 views
2

有谁知道如何以字符串方式调用方法?例如:按名称调用方法

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

.to_sym似乎不起作用。

+0

这个问题是合法的,它是关于调用一个方法,因为它的名字是在一个变量中。 – rewritten

回答

5

使用.send

t.send @setting.truck_identification.downcase 

vin应该downcase为它工作)

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 

我们通过使用不区分大小写的正则表达式的所有方法的grep,然后发送返回的第一个符号的对象,如果任何被发现。

1

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

t.send(@setting.truck_identification) 

您可能需要使用String#downcase方法正常化truck_identification。

1

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

method = @setting.truck_identification.downcase 
if t.respond_to?(method) 
    t.send(method) 
end 
+0

感谢您提供更清洁的方法。真的很感激 –