views:

51

answers:

1

Do the following two lines of code behave in exactly the same way despite slightly different implementations

values.map{ |k,v| __send__('%s=' % k.to_s, v) }
values.map{ |k,v| __send__("#{k.to_s}=", v) }

The second line would be a more common ruby idiom so I was wondering why the other method was used when this was in the Rails Core which I would expect to use idiomatic ruby.

+2  A: 

They are not absolutely identical. For instance, the first example will call String#%, so if that method is redefined for some strange reason, you might get a different result. With the standard definition of String#%, the strings computed will be the same, so both expressions will have the same result.

BTW, there's no need for to_s in this example, and assuming send has not been redefined (and is thus equivalent to __send__):

values.map{ |k,v| send("#{k}=", v) }
Marc-André Lafortune
Thanks. I'd forgotten that to_s would be called automatically within an interpolated string. I have to use `__send__` as this is within a constructor where people could pass in a key of send.
Steve Weet
Marc, you are great.
macek