Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby range: operators in case statement

I wanted to check if my_number was in a certain range, including the higher Value.

In an IF Statement I'd simply use "x > 100 && x <= 500"

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

Using:

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

doesn't work.

Note:

The standard Range doesn't include the case if my_number is exactly 500, and I don't want to add the second "when", as 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
like image 869
davegson Avatar asked Apr 17 '13 16:04

davegson


1 Answers

It should just work like you said. The below case construct includes the value 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 would you like to perform a separate action if the value is exactly 500?

like image 161
Christian-G Avatar answered Nov 04 '22 17:11

Christian-G