开发者

Why is "#{String}" a common idiom in Ruby

A Ruby dev I know asked this; my answer is below... Are there other, better reasons?

Why do so many Ruby programmers do

"#{string}"

rather than

string

since the second form is simpler and 开发者_JS百科more efficient?


Is this a common idiom for Ruby developers? I don't see it that much.


Smaller changes when you later need to do more than simply get the value of the string, but also prepend/append to it at the point of use seems to be the best motivation I can find for that idiom.


There is only one case where this is a recommended idiom :

fname = 'john'
lname  = 'doe' 
name = "#{fname} #{lname}"

The code above is more efficient than :

name = fname + ' ' + lname

or

name = [fname, lname].join(' ')


What's the broader context of some of the usages? The only thing I can come up with beyond what's already been mentioned is as a loose attempt at type safety; that is, you may receive anything as an argument, and this could ensure that whatever you pass in walks like a duck..or, well, a string (though string.to_s would arguably be clearer).

In general though, this is probably a code smell that someone along the way thought was Best Practices.


I use this kind of code, so that I can pass nil as string and it still will work on a string, rather than seeing some exceptions flying:

def short(string = nil)
  "#{string}"[0..7]
end

And it's easier/faster to append some debug code, if it's already in quotes.

So in short: It's more convenient.


Interesting answers, everyone. I'm the developer who asked the original question. To give some more context, I see this occasionally at my current job, and also sometimes in sample code on the Rails list, with variables that are known in advance to contain strings. I could sort of understand it as a substitute for to_s, but I don't think that's what's going on here; I think people just forget that you don't need the interpolation syntax if you're just passing a string variable.

If anyone tried to tell me this was a best practice, I'd run away at top speed.


maybe it is easy way to convert any to string? Because it is the same as call to_s method. But it is quite strange way :).

a = [1,2,3]
"#{a}"
#=> "123"
a.to_s
#=> "123"


I could image this being useful in cases where the object being interpolated is not always a String, as the interpolation implicitly calls #to_s:

"#{'bla'}"           => "bla"
"#{%r([a-z])}"       => "(?-mix:[a-z])"
"#{{:bla => :blub}}" => "blablub"

May make sense when logging something, where you don't care so much about the output format, but never want an error because of a wrong argument type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜