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!
Sometimes using + is easier, but in this case you left off the exclamation point. Consider:
puts "Hello #{name}!"
vs.
puts "Hello " + name + "!"
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:
puts "Hello" + name + "!"
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:
puts "The Winner was #{name} with a score of #{score}!"
By the way, searching for "string interpolation" will probably make it easier to find things than just searching for the syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With