Range

From RubySpec

Jump to: navigation, search

A range is used to denote the concept of an interval of numbers.

Examples:

 rge = Range.new(0,5) #The numbers 0,1,2,3,4,5
 rge = (0..5) #Same thing as Range.new(0,5)

Ranges with blocks:

 sum = 0
 (0..4).each {|i| sum += i}
 puts "Sum of 0..4 is #{sum}"

Ranges with case statements:

 case (n)
 when (0..4)
   puts "n is between 0..4"
 when (4..9)
   puts "n is between 4..9"
 end

Three dots are used to exclude the upper number. Example:

 (0...5).each {|i| puts i}
Personal tools