ruby “if”语句与结尾的“then”语句有什么区别?

waxmsbnn  于 12个月前  发布在  Ruby
关注(0)|答案(5)|浏览(146)

当我们把then放在if语句的末尾时,这两个Ruby if语句之间有什么区别?

if(val == "hi") then
  something.meth("hello")
else
  something.meth("right")
end

if(val == "hi")
  something.meth("hello")
else
  something.meth("right")
end
u0sqgete

u0sqgete1#

then是一个帮助Ruby识别表达式的条件和true部分的函数。
if条件then真部else假部end
then是可选的除非你想在一行中写一个if表达式。对于跨多行的if-else-end,换行符充当分隔符,将条件语句与true部分分开

# can't use newline as delimiter, need keywords
puts if (val == 1) then '1' else 'Not 1' end

# can use newline as delimiter
puts if (val == 1)
  '1'
else
  'Not 1'
end
gmxoilav

gmxoilav2#

这里有一个与你的问题没有直接关系的快速提示:在Ruby中,没有if语句。事实上,在Ruby中,根本没有语句。“一切”都是一种表达。if表达式返回在所采用的分支中计算的最后一个表达式的值。
所以,没有必要写

if condition
  foo(something)
else
  foo(something_else)
end

这最好写成

foo(
  if condition
    something
  else
    something_else
  end
)

或者作为一个一行程序

foo(if condition then something else something_else end)

在您的示例中:

something.meth(if val == 'hi' then 'hello' else 'right' end)

注意:Ruby也有一个三元运算符(condition ? then_branch : else_branch),但这是完全不必要的,应该避免。在C语言中需要三元运算符的唯一原因是因为在C中if是一个语句,因此不能返回值。您需要三元运算符,因为它是一个表达式,并且是从条件返回值的唯一方法。但是在Ruby中,if已经是一个表达式,所以真的不需要三元运算符。

bybem2ql

bybem2ql3#

then仅在您希望将if表达式写入一行时才需要:

if val == "hi" then something.meth("hello")
else something.meth("right")
end

括号在你的例子中并不重要,你可以在任何一种情况下跳过它们。
详情请参阅《十字镐书》。

gdrx4gfi

gdrx4gfi4#

我唯一喜欢在多行if/else上使用then的时候(是的,我知道这不是必需的)是当if有多个条件时,如下所示:

if some_thing? ||
  (some_other_thing? && this_thing_too?) ||
  or_even_this_thing_right_here?
then
  some_record.do_something_awesome!
end

我发现它比这些(完全有效的)选项更具可读性:

if some_thing? || (some_other_thing? && this_thing_too?) || or_even_this_thing_right_here?
  some_record.do_something_awesome!
end

# or

if some_thing? ||
  (some_other_thing? && this_thing_too?) ||
  or_even_this_thing_right_here?
  some_record.do_something_awesome!
end

因为它提供了if的条件与条件为“truthy”时要执行的块之间的可视描述。

e5nqia27

e5nqia275#

完全没有区别。
而且,仅供参考,您的代码可以优化,

something.meth( val == 'hi' ? 'hello' : 'right' )

相关问题