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

A Ruby dev I know asked about this; See my answer below ... Are there any other better reasons?

Why So Many Ruby Programmers Do

"#{string}"

      

but not

string

      

since the second form is simpler and more efficient?

+2


a source to share


8 answers


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



+12


a source


Smaller changes where you later need to do more than just get the value of the string, but also add / add to it at the point of use, seems like the best motivation I can find for this idiom.



+3


a source


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

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

      

The above code is more efficient than:

name = fname + ' ' + lname

      

or

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

      

+3


a source


What is the broader context of some of the customs? The only other thing I can think of, beyond what has already been mentioned, is like trying to lose type safety; that is, you can take anything as an argument, and that can ensure that whatever you go for walks is like a duck ... or, well, a string (although string.to_s

it might be clearer though).

All in all, though it's probably a code smell that the person thought was "Best Practice".

+2


a source


I use this type of code so I can pass nil

as a string and it will still work on the string and not see some exceptions:

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

      

And it's easier / faster to add debug code if it's already in quotes.

So, in short: it's more convenient.

+2


a source


Maybe this is an easy way to convert any to string? Because it is the same as calling method to_s

. But this is pretty weird :).

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

      

0


a source


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

If anyone tried to tell me it was best practice, I would have escaped as quickly as possible.

0


a source


I could imagine this is useful in cases where the object being interpolated is not always a string, since the interpolation implicitly calls #to_s

:

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

      

Might make sense when registering something where you don't care that much about the output format but never want an error due to the wrong argument type.

0


a source







All Articles