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