how to use ruby " case ... when " with inequalities?

RubySwitch Statement

Ruby Problem Overview


can you do this in ruby? it seems to "miss" the cases with inequalities

 case myvar
 when  myvar < -5
    do somethingA
 when -5..-3
    do special_something_XX
 when -2..-1
    do special_something_YY
 when myvar == 0
    do somethingB
 when myvar > 0
    go somethingC
 end

Ruby Solutions


Solution 1 - Ruby

You are mixing two different types of case statements:

case var
when 1
  dosomething
when 2..3
  doSomethingElse
end

case
when var == 1
   doSomething
when var < 12
   doSomethingElse
end

Solution 2 - Ruby

   case myvar
     when  proc { |n| n < -5 }
        do somethingA
     when -5..-3
        do special_something_XX
     when -2..-1
        do special_something_YY
     when proc { |n| n == 0 }
        do somethingB
     when proc { |n| n > 0 }
        go somethingC
     end
   end

Solution 3 - Ruby

I am not personally convinced that you wouldn't be better off with if statements, but if you want a solution in that form:

Inf = 1.0/0

case myvar
when -Inf..-5
  do somethingA
when -5..-3
  do special_something_XX
when -2..-1
  do special_something_YY
when 0
  do somethingB
when 0..Inf
  do somethingC
end

My preferred solution follows. Here the order matters and you have to repeat the myvar, but it's much harder to leave out cases, you don't have to repeat each bound twice, and the strictness (< vs <= rather than .. vs ...) is much more obvious.

if myvar <= -5
  # less than -5
elsif myvar <= -3
  # between -5 and -3
elsif myvar <= -1
  # between -3 and -1
elsif myvar <= 0
  # between -1 and 0
else
  # larger than 0
end

Solution 4 - Ruby

def project_completion(percent)
 case percent
  when  percent..25
    "danger"
  when percent..50
    "warning"
  when percent..75
    "info"
  when percent..100
    "success"
  else
   "info"
  end
end

Solution 5 - Ruby

Using infinity may help

case var
when -Float::INFINITY..-1
when 0
when 1..2
when 3..Float::INFINITY
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjpwView Question on Stackoverflow
Solution 1 - RubytoolkitView Answer on Stackoverflow
Solution 2 - RubyJames Kachiro SarumahaView Answer on Stackoverflow
Solution 3 - RubyPeterView Answer on Stackoverflow
Solution 4 - RubyMajid MushtaqView Answer on Stackoverflow
Solution 5 - RubyVadym TyemirovView Answer on Stackoverflow