假设我有以下陈述:
Nitpick:那些不是陈述。它们是表达式。在 Ruby 中,一切都是表达式,没有语句。
@string += @a == @b ? "X" : "Y"
@counter += @a == @b ? 1 : -1
是否可以将语句合并为一行?
是的!在 Ruby 中,总是可以将所有内容写在一行上,而从不需要换行:
@string += @a == @b ? "X" : "Y"; @counter += @a == @b ? 1 : -1
基本上有三种情况:
用于格式化的换行符
如果换行符仅用于格式化,则可以将其删除:
a +
b
# same as:
a + b
def foo(a, b)
a + b
end
# same as:
def foo(a, b) a + b end
换行符作为表达式分隔符
如果换行符用作表达式分隔符,它可以替换为不同的表达式分隔符,例如;:
foo()
bar()
# same as:
foo(); bar()
def bar
'Hello'
end
# same as:
def bar; 'Hello' end
换行符作为复合表达式中的表达式分隔符
这是上面的一个特例。在复合表达式中,除了分号作为表达式分隔符外,还有一些关键字可以代替:
if foo
bar
else
baz
end
# same as:
if foo then bar else baz end
# or:
if foo; bar else baz end
case foo
when bar
baz
when qux
frob
end
# same as:
case foo when bar then baz when qux then frob end
# or:
case foo when bar; baz when qux; frob end
while foo
bar
end
# same as:
while foo do bar end
# or:
while foo; bar end
等等。
这是一种特殊情况:
def bar
'Hello'
end
# same as:
def bar() 'Hello' end
# the parentheses are needed to Ruby knows where the parameter list ends