Ruby range: statements in case statement

I wanted to check if my_number was in a specific range, including a higher value.

In an IF statement, I would simply use "x> 100 & x <= 500"

But what should I do in case of Ruby (switch)?

Using:

case my_number
when my_number <= 500
    puts "correct"
end

does not work.

Note:

The standard range does not include the case if my_number is exactly 500, and I do not want to add a second “when”, since I would have to write double content

case my_number
# between 100 and 500
when 100..500
    puts "Correct, do something"
when 500
    puts "Correct, do something again"
end
+5
source share
3 answers

It should work as you said. The design below caseindicates a value of 500.

case my_number
# between 100 and 500
when 100..500
    puts "Correct, do something"
end

So:

case 500
  when 100..500
    puts "Yep"
end

will return Yep

Or do you want to perform a separate action if the value is exactly 500?

+6
when -Float::INFINITY..0

:)

+3

:

(1..500).include? x

member?.

+1

All Articles