-1

I have this block of code:

if %w[ups fedex usps].include?(carrier.slug)
  send(carrier.slug).track(number)
end

Which effectively replicates:

ups.track(number)
fedex.track(number)
usps.track(number)

But what I now need is that, with instance variables:

@ups.track(number)
@fedex.track(number)
@usps.track(number)

What's the equivalent?

Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • http://stackoverflow.com/questions/1074729/get-the-value-of-an-instance-variable-given-its-name – Subhas May 21 '13 at 19:35

1 Answers1

4
if %w[ups fedex usps].include?(carrier.slug)
  var_name = "@#{carrier.slug}"
  instance_variable_get(var_name).track(number)
end

By the way, your interpretation is incorrect.

ups.track(number)
fedex.track(number)
usps.track(number)

These are treated as methods, not local variables. If there's no method ups, your code will fail (even if there is a local var with the same name).

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367