如何在Ruby中不使用'then'或'end'来编写'if'

8 ruby syntax conditional-statements

我发现在Ruby中编写相同条件的三种方法:

#1
if 1==1 
  puts "true" 
end

#2
puts "true" if 1==1

#3
if 1==1  then puts "true" end
Run Code Online (Sandbox Code Playgroud)

为什么我不能这样做?

#4
if 1==1 puts "true"
Run Code Online (Sandbox Code Playgroud)

我不明白:

  1. 为什么然后和结束都需要在#3和,
  2. 为什么我需要更改订单以使#2工作.

声明#4似乎是最自然的写作方式.我不明白为什么不可能.

Chu*_*uck 19

" if x then y end"语法用于多行条件,而" y if x"形式用于简洁的单行条件语句.的then是在第一种情况下,以告诉红宝石条件已被超过(因为红宝石不需要像C括号)必需的,并且end有必要告诉红宝石,整个if块结束(因为它可以是多行).

您可以用then分号替换,因为行尾也表示条件的结束.你无法摆脱end多线if.如果你想要一个简洁的单行,可以使用第二种形式或三元运算符.

例如,假设

x = true
Run Code Online (Sandbox Code Playgroud)

以下将评估为真,并返回y

x ? y :
=> y
Run Code Online (Sandbox Code Playgroud)

同样,这将评估错误并且不返回任何内容

!x ? y :
=> 
Run Code Online (Sandbox Code Playgroud)

在else案例的':'之后添加一个术语

!x ? y : z
=> z
Run Code Online (Sandbox Code Playgroud)