0

快速提问。有没有更优雅的方式来写这样的东西?

result = a <=> b

if result == 1
  # do something
elsif result == 0
  # do something else
else
  # do something else
end
4

2 回答 2

1

您可以使用以下case语句

case a <=> b
  when 1
    # do something
  when 0
    # do something else
  when -1
    # do something else
  else
    # return / catch error
end

对于简单的一个衬里,您也可以缩短它then

case a <=> b
  when 1 then x = "foo"
  when 0 then y = "bar"
  when -1 then z = "foobar"
  else # return / catch error
end
于 2014-12-13T13:33:52.407 回答
0

我不知道这是否更优雅,但它肯定更直接:

case
when a < b
  # do A
when a > b
  # do B
else
  # do C
end
于 2014-12-13T19:32:31.490 回答