有谁知道如何以字符串方式调用方法?例如:按名称调用方法
case @setting.truck_identification
when "Make"
t.make
when "VIN"
t.VIN
when "Model"
t.model
when "Registration"
t.registration
.to_sym
似乎不起作用。
有谁知道如何以字符串方式调用方法?例如:按名称调用方法
case @setting.truck_identification
when "Make"
t.make
when "VIN"
t.VIN
when "Model"
t.model
when "Registration"
t.registration
.to_sym
似乎不起作用。
使用.send
:
t.send @setting.truck_identification.downcase
(vin
应该downcase为它工作)
你会想用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,然后发送返回的第一个符号的对象,如果任何被发现。
您可以使用Object#send
方法将方法名称作为字符串传递。 例如:
t.send(@setting.truck_identification)
您可能需要使用String#downcase
方法正常化truck_identification。
通过这些方法的清理并不是最干净的方法。只是使用#respond_to?()
method = @setting.truck_identification.downcase
if t.respond_to?(method)
t.send(method)
end
感谢您提供更清洁的方法。真的很感激 –
这个问题是合法的,它是关于调用一个方法,因为它的名字是在一个变量中。 – rewritten