有誰知道如何以字符串方式調用方法?例如:按名稱調用方法
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