Ruby range: operators in case statement

前端 未结 4 367
萌比男神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:06

    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?

    0 讨论(0)
  • 2021-01-18 07:23
    when -Float::INFINITY..0
    

    Would do the trick :)

    0 讨论(0)
  • 2021-01-18 07:23

    You could just do:

    (1..500).include? x
    

    which is also aliased as member?.

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题