tags:

views:

243

answers:

6

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 more efficient?

+3  A: 

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.

Tetsujin no Oni
It's a piss-poor motivation, mind you, but it's one I could hear a PHB pronouncing as a reason to do it.
Tetsujin no Oni
LOL at PHB attempt to understand what makes programmers more efficient :)
dasil003
+7  A: 

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

ScottD
Perhaps it's a common idiom among programmers coming from a specific background into ruby? I'm relaying a question here, so I'm perfectly comfortable with the "It isn't that common, and it's just as wrong as you're thinking it is" answer.
Tetsujin no Oni
A: 

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"
fl00r
#{a} is 4 keystrokes.a.to_s is 6 keystrokesSaves 2 keystrokes. That'd be taking the definition of "easy" very literally though ;-).
Robbie
Yep, It is just suggestion :) I am not fan of using topic "idiom"
fl00r
Problem is that a.to_s in Ruby 1.9 doesn't do that.
ScottD
@ScottD - it doesn't do it in Ruby 1.8, either, for that matter. At least, not for me.
Matchu
In case of Array, it will return of course "123" (not "1,2,3").
fl00r
+1  A: 

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.

Marc Bollinger
A: 

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.

Marnen Laibow-Koser
+1  A: 

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(' ')
Alain Ravet