if当我们then在if语句的末尾添加一个时,这两个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)
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已经是一个表达式,所以实际上不需要三元运算符.
我唯一喜欢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以及条件为“真”时要执行的块。
的then,如果你想要写的只需要if在一行表达式:
if val == "hi" then something.meth("hello")
else something.meth("right")
end
Run Code Online (Sandbox Code Playgroud)
您的示例中的括号不重要,您可以在任何一种情况下跳过它们.
有关详细信息,请参阅Pickaxe Book.
| 归档时间: |
|
| 查看次数: |
28571 次 |
| 最近记录: |