The operation #{ }
appears to be so fundamental that my Ruby book completely skips its definition. Can someone provide an explanation?
Noun (UNCOUNTABLE)Faulty or improper care.
Adverb. In a definitional manner; as a definition.
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.
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}"
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