"if"语句与"then"结尾有什么区别?

Mo.*_*Mo. 56 ruby

if当我们thenif语句的末尾添加一个时,这两个Ruby 语句之间的区别是什么?

if(val == "hi") then
  something.meth("hello")
else
  something.meth("right")
end
Run Code Online (Sandbox Code Playgroud)

if(val == "hi")
  something.meth("hello")
else
  something.meth("right")
end
Run Code Online (Sandbox Code Playgroud)

Gis*_*shu 68

then 是一个分隔符,帮助Ruby识别条件和表达式的真实部分.

if条件then真实部分else假部分end

then是可选的,除非你想if在一行中写一个表达式.对于跨越多行的if-else-end,换行符充当分隔符以将条件与真实部分分开

# 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
Run Code Online (Sandbox Code Playgroud)

  • @Jorg - 对.我需要一些时间来磨掉C年.:) (3认同)

Jör*_*tag 12

这是一个与你的问题没有直接关系的快速提示:在Ruby中,没有if声明这样的东西.事实上,在Ruby中,没有报表在所有.一切都是表达.if表达式返回在所采用的分支中计算的最后一个表达式的值.

所以,没有必要写

if condition
  foo(something)
else
  foo(something_else)
end
Run Code Online (Sandbox Code Playgroud)

这最好写成

foo(
  if condition
    something
  else
    something_else
  end
)
Run Code Online (Sandbox Code Playgroud)

或者作为一个班轮

foo(if condition then something else something_else end)
Run Code Online (Sandbox Code Playgroud)

在你的例子中:

something.meth(if val == 'hi' then 'hello' else 'right' end)
Run Code Online (Sandbox Code Playgroud)

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

  • 在Ruby中,有很多方法可以实现相同的目标.我个人喜欢三元运算符.我觉得它紧凑可读:) (6认同)
  • 可读性对于高质量的代码至关重要。在参数列表中嵌套多行分支构造(无论是语句还是表达式)是荒谬的。甚至需要大量的扫描和考虑才能对正在发生的事情有一个高层次的了解。多花一些额外的击键时间,并减少一点 DRY,让您的代码更具可读性和可支持性。潜入(简单)三元运算符不会违反可读性,也不会在拉取请求中被拒绝。 (3认同)
  • 我们在构建系统中广泛使用 ruby​​,我发现第一种语法对于来自其他语言的开发人员来说更容易理解。 (2认同)

jef*_*ll2 7

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

if some_thing? ||
  (some_other_thing? && this_thing_too?) ||
  or_even_this_thing_right_here?
then
  some_record.do_something_awesome!
end
Run Code Online (Sandbox Code Playgroud)

我发现它比这些(完全有效)选项中的任何一个都更具可读性:

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
Run Code Online (Sandbox Code Playgroud)

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


Dou*_*las 6

then,如果你想要写的只需要if在一行表达式:

if val == "hi" then something.meth("hello")
else something.meth("right")
end
Run Code Online (Sandbox Code Playgroud)

您的示例中的括号不重要,您可以在任何一种情况下跳过它们.

有关详细信息,请参阅Pickaxe Book.