开发者

Are Ruby formatted strings and interpolated strings identical in behaviour?

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.


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) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜