我可以在Ruby的if/else中使用大括号吗?

Jee*_*eet 6 ruby

为什么我不能在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)

我仍然建议小心缩进,但是即使正确使用大括号,很难缩进的代码也会欺骗人类读者.

  • @iAdam:你的意思是你有很多缩进级别吗?这就是为什么你应该将你的代码重构为小而可读的部分,即.方法. (2认同)
  • 如果你有一个大的构造,你的构造做得太多了.也许快速浏览常见的代码气味:http://en.wikipedia.org/wiki/Code_smell (2认同)

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)


Pau*_*ber 4

没有。您需要使用end而不是}.