代码布局
Ruby 中的表达式以换行符分隔
x = 1 y = 2 z = x + y
换行符也用作某些控制结构标题与其主体之间的逻辑分隔符
if z > 3 # line break ends the condition and starts the body puts "more" end while x < 3 # line break ends the condition and starts the body x += 1 end
; 可用作表达式分隔符,代替换行符
x = 1; y = 2; z = x + y if z > 3; puts "more"; end
传统上,以 ; 分隔的表达式仅用于短脚本和实验。
在某些控制结构中,有一个可选关键字,可以用来分隔其元素,而不是使用换行符
# if, elsif, until and case ... when: 'then' is an optional separator: if z > 3 then puts "more" end case x when Numeric then "number" when String then "string" else "object" end # while and until: 'do' is an optional separator while x < 3 do x +=1 end
此外,在某些不会造成歧义的地方可以省略换行符。请注意上面的示例:end 前不需要换行符,就像 else 后不需要换行符一样。
在行中断表达式
一个表达式可能被分成几行,当每一行都可以明确地识别为“不完整”而没有下一行时。
这些可以正常工作
x = # incomplete without something after = 1 + # incomplete without something after + 2 File.read "test.txt", # incomplete without something after , enconding: "utf-8"
这些将无法工作
# unintended interpretation:
x = 1 # already complete expression
+ 2 # interpreted as a separate +2
# syntax error:
File.read "test.txt" # already complete expression
, encoding: "utf-8" # attempt to parse as a new expression, SyntaxError
规则的例外情况是,以 .(“前导点”风格的方法调用)或逻辑运算符 &&/|| 和 and/or 开头的行
# OK, interpreted as a chain of calls File.read('test.txt') .strip("\n") .split("\t") .sort # OK, interpreted as a chain of logical operators: File.empty?('test.txt') || File.size('test.txt') < 10 || File.read('test.txt').strip.empty?
如果表达式以上述任何方式拆分成多行,则允许在单独的行之间插入注释
sum = base_salary + # see "yearly bonuses section" yearly_bonus(year) + # per-employee coefficient is described # in another module personal_coeff(employee) # We want to short-circuit on empty files File.empty?('test.txt') # Or almost empty ones || File.size('test.txt') < 10 # Otherwise we check if it is full of spaces || File.read('test.txt').strip.empty?
最后,代码可以通过 \ 显式告知 Ruby 该表达式将继续到下一行
# Unusual, but works File.read "test.txt" \ , encoding: "utf-8" # More regular usage (joins the strings on parsing instead # of concatenating them in runtime, as + would do): TEXT = "One pretty long line" \ "one more long line" \ "one other line of the text"
\ 在解析时充当换行符转义,因此不能在它们之间插入注释
TEXT = "line 1" \ # here would be line 2: "line 2" # This is interpreted as if there was no line break where \ is, # i.e. the same as TEXT = "line 1" # here would be line 2: "line 2" puts TEXT #=> "line 1"