LoginSignup
22
20

More than 5 years have passed since last update.

Ruby で無限 Range

Last updated at Posted at 2012-07-06

Ruby の Range は無限大を扱うことができます.

(-Float::INFINITY..Float::INFINITY) #=> -Infinity..Infinity

(0..Float::INFINITY) === 817049871230948719384719274389123874198741 #=> true
(0..Float::INFINITY) === -1 #=> false

# 負の無限大も OK
(-Float::INFINITY..0) === -841794879213748747847321751947365 #=> true

どういう時に使うのかというと,case 文の when 節では === でマッチングを行うので,そこで使えます.

a = 10000

case a
when 0 ... 100
  "0 〜 99"
when 100 ... 1000
  "100 〜 999"
when 1000 .. Float::INFINITY
  "1000以上"
else
  "負数"
end

#=> "1000以上"
22
20
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
20