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.

1 Answer 1

2

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) }
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.