Ruby 反斜杠在新行上继续字符串? [英] Ruby backslash to continue string on a new line?

查看:47
本文介绍了Ruby 反斜杠在新行上继续字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查拉取请求中的一行 Ruby 代码.我不确定这是否是我以前从未见过的错误或功能:

I'm reviewing a line of Ruby code in a pull request. I'm not sure if this is a bug or a feature that I haven't seen before:

puts "A string of Ruby that"\
  "continues on the next line"

反斜杠是连接这些字符串的有效字符吗?或者这是一个错误?

Is the backslash a valid character to concatenate these strings? Or is this a bug?

推荐答案

这是有效的代码.

反斜杠是换行符.您的代码有两个带引号的文本;这些运行看起来像两个字符串,但实际上只是一个字符串,因为 Ruby 连接了以空格分隔的运行.

The backslash is a line continuation. Your code has two quoted runs of text; the runs appear like two strings, but are really just one string because Ruby concatenates whitespace-separated runs.

实际上只是一个字符串的三段带引号的文本示例:

Example of three quoted runs of text that are really just one string:

"a" "b" "c"
=> "abc"

使用 \ 续行的三个带引号的文本的示例,实际上只是一个字符串:

Example of three quoted runs of text that are really just one string, using \ line continuations:

"a" \
"b" \
"c"
=> "abc"

三个字符串的示例,使用 + 行连续和串联:

Example of three strings, using + line continuations and also concatenations:

"a" +
"b" +
"c"
=> "abc"

其他续行细节:Ruby 将分号和换行符解释为语句的结尾.但是,如果 Ruby 在行尾遇到诸如 +、- 或反斜杠之类的运算符,它们表示继续陈述."- Ruby 快速指南

Other line continuation details: "Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement." - Ruby Quick Guide

这篇关于Ruby 反斜杠在新行上继续字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆