简体   繁体   中英

Backslash in Ruby conditional statement

I was browsing some code and spotted this:

stem = ""

answer = ""

return if stem.nil? || answer.nil? || \
          stem.question == answer.question

What is the \\ for? I know \\ is used in strings, but I've never seen a use-case for this before. Is this a syntax error or some advanced ruby syntax? Am I missing something?

It's a useless line-continuation character.

The question "is it a syntax error" seems pretty simple to discover.

\\ is used to indicate line continuation in ruby. Using \\ will strip the \\n (newline) character.

Example (Using string):

Without \\ :

2.1.2-perf :018 > s = "test this
2.1.2-perf :019"> out"
 => "test this\nout"

With \\ :

2.1.2-perf :020 > s = "test this \
2.1.2-perf :021"> out"
 => "test this out"

Example (without using string):

Without \\ :

2.1.2-perf :043 > return "test" if true && false &&
2.1.2-perf :044 >   true
 => nil

With \\ :

2.1.2-perf :045 > return "test" if true && false && \
2.1.2-perf :046 >   true
 => nil

In your case, it wouldn't matter, but it is not a syntax error.

From the doc :

Ruby programs are sequence of expressions. Each expression are delimited by semicolons(;) or newlines. Backslashes at the end of line does not terminate expression.

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