简体   繁体   中英

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

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?

when -Float::INFINITY..0

会做的伎俩:)

You could just do:

(1..500).include? x

which is also aliased as member? .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM