简体   繁体   中英

Is it necessary to escape double quotes used within Ruby string interpolation?

Given the following Ruby code:

my_array = %w(one two three)
logger.info "Backtrace:\n#{my_array.join("\n")}"

Expected Output:

Backtrace:
one
two
three

Is it necessary to escape the double quoted "\\n" or would that result in the opposite effect?

No, the stuff inside #{...} inside a double quoted string (or other-quoted string that behaves like a double quoted string) is just Ruby so double quoted strings inside #{...} are just plain old double quoted strings. In particular, this:

s = "#{"\n"}"

will put a single newline into s .

I would recommend trying such short code passages using irb which reads and interprets Ruby code on-the-fly.

Regarding your question:

my_array = %w(one two three)
logger.info "Backtrace:\n#{my_array.join("\n")}"

is the correct syntax, and:

my_array = %w(one two three)
logger.info "Backtrace:\n#{my_array.join(\"\n\")}"

will not work. The #{} causes everything inside to be treated as a normal Ruby expression without need of special escaping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM