I'm doing the Ruby 20 minute tutorial on ruby-lang.org and I came across this code messing with the irb:
irb(main):015:0> def h(name)
irb(main):016:1> puts "Hello #{name}!"
irb(main):017:1> end
based on the explanation, the #{name}
part is just adding the variable to the string? I thought this was an odd and verbose way of writing it so I just thought I'd try "Hello" + name
and it worked exactly the same way..
I googled around trying to find a meaning to #{}
and I cant find anything talking about it so I thought I'd ask the community.. what is the difference? Is there one?
Thanks in advance!
The #{} is used for string interpolation, which allows you to easily and clearly put data in your strings. Ruby evaluates the content within the curly braces and then calls its
to_s
method, which every Ruby object inherits from Object.This allows you to even do calculations within your strings, e.g.
It's important to note that it's not just readability. Using string interpolation will do the right thing e.g. call
to_s
on the whatever is between#{}
As opposed to
String interpolation is almost always much easier to read, particularly if there's multiple values to interp.
It may become difficult if the value being interpolated is verbose:
In cases like that, you might want to concatenate, or just use a temp variable.
Sometimes using
+
is easier, but in this case you left off the exclamation point. Consider:vs.
I find the first more readable, especially when used several times in a string.
Also consider how easy it was to leave out the space after "Hello" in the second version:
is easy to write, but probably isn't what you mean.
Last, it makes an even bigger difference when what you're interpolating isn't a string:
By the way, searching for "string interpolation" will probably make it easier to find things than just searching for the syntax.
The biggest differences are ease of reading, conformance to idiomatic usage, and speed.
When using
"Hello " + name + "!"
you (well, the Ruby interpreter) creates a total of 3 additional strings, as opposed to"Hello #{name}!"
where it only creates one additional string.Keep in mind that using string interpolation (
"#{}"
) automatically calls#to_s
, which may or may not be desired.See this SO question for more information.