Ruby range: operators in case statement

前端 未结 4 399
萌比男神i
萌比男神i 2021-01-18 06:29

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

4条回答
  •  情深已故
    2021-01-18 07:29

    Here's a case way to capture "x > 100 && x <= 500 as desired: a value in a closed range with the start value excluded and the end value included. Also, capturing the ranges before and after that is shown.

    case my_number
    when ..100;         puts '≤100'
    when   100..500;    puts '>100 and ≤500'
    when        500..;  puts '>500'
    end
    
    

    Explanations:

    • Ranges wit one end left out start from -Infinity resp. go to Infinity. This was introduced in Ruby 2.6.
    • Ranges x..y include the end value, ranges x...y exclude the end value.
    • All ranges include the start value. To create the equivalent of a range without the start value, you can capture the start value in a preceding when case. That is how the second when case is equivalent to your "x > 100 && x <= 500 even though (100..500).include? 100. Similarly for the third case.

提交回复
热议问题