Spaceship operator and conditional statements

344 views Asked by At

Quick question. Is there more elegant way to write something like this?

result = a <=> b

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

There are 2 answers

0
davegson On BEST ANSWER

You can use the case statement:

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

For simple one liners you can also shorten it with then

case a <=> b
  when 1 then x = "foo"
  when 0 then y = "bar"
  when -1 then z = "foobar"
  else # return / catch error
end
0
Cary Swoveland On

I don't know if this is more elegant, but it certainly is more direct:

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