为什么我不能在if/ elseconstructs中使用花括号?我离开了Python,因为我觉得不能轻易地缩进语句.
这在Ruby中也是这样吗?
例如,我可以写这样的东西吗?
if token == "hello" {
puts "hello encountered"
# lots of lines here
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用大括号来做到这一点?我也读过有关块但不确定如何在if/ else表达式中使用它们.
Chu*_*uck 15
你不能使用花括号,但缩进也无关紧要.Ruby使用end关键字而不是结束括号.
if token == "hello"
puts "hello encountered"
# lots of lines here
end
Run Code Online (Sandbox Code Playgroud)
我仍然建议小心缩进,但是即使正确使用大括号,很难缩进的代码也会欺骗人类读者.
hor*_*guy 13
这好可爱:
def my_if(condition, &block)
block.call if condition
end
Run Code Online (Sandbox Code Playgroud)
使用方法如下:
my_if(token == "hello") {
puts "hello encountered!"
}
Run Code Online (Sandbox Code Playgroud)