Does anyone know how to call a method as a string? For example:
case @setting.truck_identification
when "Make"
t.make
when "VIN"
t.VIN
when "Model"
t.model
when "Registration"
t.registration
.to_sym
does not seem to work.
Does anyone know how to call a method as a string? For example:
case @setting.truck_identification
when "Make"
t.make
when "VIN"
t.VIN
when "Model"
t.model
when "Registration"
t.registration
.to_sym
does not seem to work.
use .send
:
t.send @setting.truck_identification.downcase
(vin
should be downcase for it to work)
You're going to want to use Object#send
, but you'll need to call it with the correct casing. For example:
[1,2,3].send('length')
=> 3
Edit: Additionally, though I would hesitate recommend it because it seems like bad practice that will lead to unexpected bugs, you can deal with different casing by searching through a list of methods that the object supports.
method = [1,2,3].methods.grep(/LENGth/i).first
[1,2,3].send(method) if method
=> 3
We grep through all methods using a case-insensitive regex, and then send the first returned symbol to the object if any was found.
You can use Object#send
method to pass the method name as string.
For example:
t.send(@setting.truck_identification)
You might need to normalize the truck_identification with String#downcase
method.
Grepping through the methods isn't the cleanest way to do it. Just use #respond_to?()
method = @setting.truck_identification.downcase
if t.respond_to?(method)
t.send(method)
end