A shortcut to make case / switch returns a value

I'm sure I saw someone doing a quick access technique like the code below (which doesn't work)

return case guess
  when guess > @answer then :high
  when guess < @answer then :low
  else :correct
end

Does anyone know the trick I'm talking about?

+4
source share
4 answers

It works:

return case
  when guess > @answer ; :high
  when guess < @answer ; :low
  else ; :correct
  end
+4
source
Operator

A casereturns a value, you just need to use the correct form to get the expected value.

There are two forms in Ruby case. The first is as follows:

case expr
when expr1 then ...
when expr2 then ...
else ...
end

This will compare the expression exprwith the expression whenusing ===(this is a triple BTW) and it will execute the first thenone where ===it gives the true value. For example:

case obj
when Array then do_array_things_to(obj)
when Hash  then do_hash_things_to(obj)
else raise 'nonsense!'
end

:

if(Array === obj)
  do_array_things_to(obj)
elsif(Hash === obj)
  do_hash_things_to(obj)
else
  raise 'nonsense!'
end

case - :

case
when expr1 then ...
when expr2 then ...
else ...
end

:

case
when guess > @answer then :high
when guess < @answer then :low
else :correct
end

:

if(guess > @answer)
  :high
elsif(guess < @answer)
  :low
else
  :correct
end

, , , ( ) :

(guess > @answer) === guess
(guess < @answer) === guess

case , .

+12

guess case, ruby.

:

def test value
  case 
  when value > 3
    :more_than_3
  when value < 0
    :negative
  else
    :other
  end
end

test 2   #=> :other 
test 22  #=> :more_than_3 
test -2  #=> :negative 

return .

: then, , :

def test value
  case 
    when value > 3 then :more_than_3
    when value < 0 then :negative
    else :other
  end
end
+5

@mu (, ), , , :

return case (guess <=> @answer)
       when -1 then :low
       when  0 then :correct
       when  1 then :high
       end

       ...
       else
         :high
       end
0
source

All Articles