Reputation: 1981
The operation #{ }
appears to be so fundamental that my Ruby book completely skips its definition. Can someone provide an explanation?
Upvotes: 39
Views: 32302
Reputation: 84453
This is a tough question to Google for unless you know the right search terms. The #{}
operator technically performs expression substitution inside a string literal.
The #{}
literal is the operator used for interpolation inside double-quoted strings the same way that the backticks or $()
construct would be used in Bash. From a practical point of view, the expression inside the literal is evaluated, and then the entire #{}
expression (including both the operator and the expression it contains) is replaced in situ with the result.
Upvotes: 59
Reputation: 62542
It allows you to put Ruby code within a string. So:
"three plus three is #{3+3}"
Would output:
"three plus three is 6"
It's commonly used to insert variable values into strings without having to mess around with string concatenation:
"Your username is #{user}"
Upvotes: 14
Reputation: 42207
It's the string interpolation operator, you use it to insert an expression into a string. Your string needs to be embedded in " to let this magic work, no 's. It is much faster and better than string concatenation.
var = "variable"
"this is a string with a #{var} in" => "this is a string with a variable in"
Upvotes: 6