Toaster
Toaster

Reputation: 1981

Meaning of #{ } in Ruby?

The operation #{ } appears to be so fundamental that my Ruby book completely skips its definition. Can someone provide an explanation?

Upvotes: 39

Views: 32302

Answers (3)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84453

Why This Is a Good Question

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 Answer

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.

Related Links

Upvotes: 59

Sean
Sean

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

peter
peter

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

Related Questions