2

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.

rewritten
  • 16,280
  • 2
  • 47
  • 50
Jackie Chan
  • 2,654
  • 6
  • 35
  • 70

4 Answers4

5

use .send:

t.send @setting.truck_identification.downcase

(vin should be downcase for it to work)

rewritten
  • 16,280
  • 2
  • 47
  • 50
2

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.

ceyko
  • 4,822
  • 1
  • 18
  • 23
1

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.

Ahmed Al Hafoudh
  • 8,281
  • 1
  • 18
  • 34
1

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
Sergio Carneiro
  • 3,726
  • 4
  • 35
  • 51