Ruby 中条件表达式的语法是:
if c_1 then e_1 elsif c_2 then e_2 elsif c_3 then e_3 … elsif c_n then e_n else e_nplus1 end
c_1 … c_n 和 e_1 … e_nplus1 可以是任意 Ruby 表达式。
可以使用表达式分隔符(即; 或换行符)代替then 关键字来分隔条件表达式的各个部分。
带分号(这种用法不习惯):
if c_1; e_1 elsif c_2; e_2 elsif c_3; e_3 … elsif c_n; e_n else e_nplus1 end
使用换行符:
if c_1
e_1
elsif c_2
e_2
elsif c_3
e_3
# …
elsif c_n
e_n
else
e_nplus1
end
如果您使用换行符,您还可以选择使用 then 关键字,但这也不是惯用的:
if c_1
then e_1
elsif c_2
then e_2
elsif c_3
then e_3
# …
elsif c_n
then e_n
else
e_nplus1
end
因此,在您的情况下,正确的语法是:
# idiomatic
a.each { |i| if i % 3 == 0 then puts "three" elsif i % 5 == 0 then puts "five" else puts i end }
# non-idiomatic
a.each { |i| if i % 3 == 0; puts "three" elsif i % 5 == 0; puts "five" else puts i end }
# idiomatic
a.each { |i|
if i % 3 == 0
puts "three"
elsif i % 5 == 0
puts "five"
else
puts i
end
}
# non-idiomatic
a.each { |i|
if i % 3 == 0
then puts "three"
elsif i % 5 == 0
then puts "five"
else
puts i
end
}
但是,对于这样的if / elsif 链,使用case 表达式通常更惯用:
# idiomatic
case when c_1 then e_1 when c_2 then e_2 when c_3 then e_3 … when c_n then e_n else e_nplus1 end
# non-idiomatic
case when c_1; e_1 when c_2; e_2 when c_3; e_3 … when c_n; e_n else e_nplus1 end
# idiomatic
case
when c_1
e_1
when c_2
e_2
when c_3
e_3
# …
when c_n
e_n
else
e_nplus1
end
# non-idiomatic
case
when c_1
then e_1
when c_2
then e_2
when c_3
then e_3
# …
when c_n
then e_n
else
e_nplus1
end
在你的情况下看起来像这样:
# idiomatic
a.each { |i| case when i % 3 == 0 then puts "three" when i % 5 == 0 then puts "five" else puts i end }
# non-idiomatic
a.each { |i| case when i % 3 == 0; puts "three" when i % 5 == 0; puts "five" else puts i end }
# idiomatic
a.each { |i|
case
when i % 3 == 0
puts "three"
when i % 5 == 0
puts "five"
else
puts i
end
}
# non-idiomatic
a.each { |i|
case
when i % 3 == 0
then puts "three"
when i % 5 == 0
then puts "five"
else
puts i
end
}
请注意,条件表达式(if 和 case)是表达式,而不是语句。 Ruby 中没有语句,一切都是表达式,一切都计算为一个值。条件表达式的计算结果为所采用分支中表达式的值。
所以,你也可以这样写:
# idiomatic
a.each { |i| puts(if i % 3 == 0 then "three" elsif i % 5 == 0 then "five" else i end) }
# non-idiomatic
a.each { |i| puts(if i % 3 == 0; "three" elsif i % 5 == 0; "five" else i end) }
# idiomatic
a.each { |i|
puts(if i % 3 == 0
"three"
elsif i % 5 == 0
"five"
else
i
end)
}
# non-idiomatic
a.each { |i|
puts(if i % 3 == 0
then "three"
elsif i % 5 == 0
then "five"
else
i
end)
}
# idiomatic
a.each { |i| puts(case when i % 3 == 0 then "three" when i % 5 == 0 then "five" else i end) }
# non-idiomatic
a.each { |i| puts(case when i % 3 == 0; "three" when i % 5 == 0; "five" else i end) }
# idiomatic
a.each { |i|
puts(case
when i % 3 == 0
"three"
when i % 5 == 0
"five"
else
i
end)
}
# non-idiomatic
a.each { |i|
puts(case
when i % 3 == 0
then "three"
when i % 5 == 0
then "five"
else
i
end)
}