5

I have a string like this:

'say "Twenty-five minutes remaining."'

How would I interpolate more dynamic content into that message? I already know the approach below doesn't work, as the content is returned literally.

'say "#{minutes_remaining} minutes remaining."'

2 Answers 2

8

This works:

minutes_remaining = 25
system("say '#{minutes_remaining} minutes remaining.'")

String interpolation only works with double quotes, not single quotes.

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

9 Comments

That is not what the OP originally wanted. What was wanted is "say \"#{minutes_remaining} minutes remaining.\"".
@sawa: She's happy with the solution. Do you claim to know better what she wanted? :)
@SergioTulentsev My comment is based on what the OP wrote in the question. It is written using double quote around the substring, and if the OP is still happy with single quotation, then that shows sloppiness on the OP.
@Mischa In the first example, the OP has "Twenty-five minutes remaining.", which indicates that that part is expected to be literally double quoted. The OP continued to try to use double quotation in "#{minutes_remaining} minutes remaining.", but the problem was that interpolation has to be passed on to the entire string, which means the entire string must be double quoted, and that will interfere with the literal double quotes that is needed inside the string. Your answer switched the expected literal double quotes with single quotes. I don't understand what your problem is.
+1 to @sawa's example as it elucidates the use of interpolating double-quotes within a double-quoted string by escaping the nested double-quotes.
|
7

You can escape the double quotes with backslashes:

puts "say \"#{minutes_remaining} minutes remaining.\""

Or even better, use %{}, without needing to escape double quotes

puts %{say "#{minutes_remaining} minutes remaining."}

related question Escaping single and double quotes in a string in ruby?

Comments

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.