太空飞船运营商和条件声明

时间:2014-12-13 13:26:03

标签: ruby conditional-statements spaceship-operator

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

result = a <=> b

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

2 个答案:

答案 0 :(得分:1)

您可以使用case statement

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

答案 1 :(得分:0)

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

case
when a < b
  # do A
when a > b
  # do B
else
  # do C
end