多线如果是红宝石

时间:2013-04-21 22:42:12

标签: ruby if-statement block

我知道其他地方已经触及了这些问题,但我对ruby中多行(块?)if else语句的正确语法感到有些困惑。

举个例子:

if condition then
  do something
  do somethingelse
  do yetanotherthing
  done
else
  do acompletelyunrelatedthing
done

我了解如果使用多行,则then语句是必需的,但done必须在else之前?这似乎会突破if...else上下文。当我确实包括这个done时,我得到了:

syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'

当我不包括它时,我得到:

syntax error, unexpected keyword_else, expecting keyword_end

2 个答案:

答案 0 :(得分:5)

嗯...... Ruby中没有done个关键字。这是正确的语法:

if condition
  # do stuff
else
  # do other stuff
end

也不需要then关键字。

答案 1 :(得分:0)

then关键字仅在您需要将整个事物放在一行上时使用(将条件与要采取的操作分开,如果为真):

if condition then do_something else do_something_different end

如果您不想要一行(通常不需要),则语法与Doorknob的答案一样。

相关问题