2

I'm messing around with Ruby and I'm trying to understand how the #{} operation works.

b = "puts \'Hello World\'"
r = "Testing .... #{b}"

When running this code, nothing its printed to the screen.

However this does print to the screen

b = "puts \'Hello World\'"
r = "Testing .... #{puts 'Hello World'}"

Why does the 2nd example print to the screen and the first doesn't.

Thanks

1
  • 3
    This is like if your entire program was "puts 'Hello World'" vs. puts 'Hello World'. Sure, both programs contain puts, but in one of them it’s code and in the other it’s just part of a string literal. Commented Oct 15, 2018 at 0:03

1 Answer 1

6

String interpolation (the #{} operation) evaluates everything between those braces as code and converts the returned value from execution to a string and places that string in the place of the #{}.

In the first example the string r includes b, and b is just the string "puts \'Hello World\'". In this case, "puts" has no special meaning because it is just a string. So in this first case, r becomes:

"Testing .... #{"puts \'Hello World\'"}"

which then becomes:

"Testing .... puts \'Hello World\'"

In the second example you are including the final value from executing puts 'Hello World' within the string r. Since puts returns nil, r becomes

"Testing .... #{nil}"

which then becomes:

"Testing .... "
Sign up to request clarification or add additional context in comments.

3 Comments

Ah ok this makes sense. Is there a way to get the first example to work? I guess you’d have to get it to execute first like the second. Is that possible with a variable that is a string?
@CBaker I'm not sure what your expected behavior is. If you want r to be the string "Testing .... puts \'Hello World\'", and you want that to be printed, you can just do puts r. Can you explain a bit more about what you want to have happen?
@CBaker you could wrap the code in a proc: b = -> { puts 'hello' } and call that from within the string: r = "Testing #{b.call}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.