How does "unless" work in Ruby?

lam*_*ade -2 ruby

I would like to refactor:

def play_as_dealer
  if value < 16
      hit!(deck)
      play_as_dealer
   end
end
Run Code Online (Sandbox Code Playgroud)

to this version

def play_as_dealer
  hit!(deck) unless value > 16
  play_as_dealer
end
Run Code Online (Sandbox Code Playgroud)

My version with the unless statement does not work. Why is that?

wal*_*pus 7

语义command unless condition相当于command if !condition.当且仅当条件逻辑为假时才执行该命令,而不是if表达式,如果条件为真,则执行该命令.

例如,您可以使用翻译,除非像这样:

def play_as_dealer
  unless value >= 16
    hit!(deck)
    play_as_dealer
  end
end
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您使用的是表达式的内联版本,其中unless限制仅对该行中的前一个表达式有效.如果您需要限制两个或更多命令,请使用上面示例中的表单.