Ruby Ranges

by

in

Ruby range represents a set of values with a beginning and an end. They can be constructed using s..e and s…e literals or with ::new.

The ranges which has .. in them, run from beginning to end inclusively. The ranges which has … in them, run exclusively the end value.

puts (-5..-1).to_a       

puts (-5...-1).to_a       

puts ('a'..'e').to_a      

puts ('a'...'e').to_a

Output:

Ruby rangers 1

Ruby has a variety of ways to define ranges.

  • Ranges as sequences
  • Ranges as conditions
  • Ranges as intervals

Ranges as Sequences

The most natural way to define a range is in sequence. They have a start point and an end point. They are created using either .. or … operators.

We are taking a sample range from 0 to 5. The following operations are performed on this range.

Example:


  1. #!/usr/bin/ruby   
  2.   
  3. range = 0..5   
  4.   
  5. puts range.include?(3)   
  6. ans = range.min   
  7. puts "Minimum value is #{ans}"   
  8.   
  9. ans = range.max   
  10. puts "Maximum value is #{ans}"   
  11.   
  12. ans = range.reject {|i| i < 5 }   
  13. puts "Rejected values are #{ans}"   
  14.   
  15. range.each do |digit|   
  16.    puts "In Loop #{digit}"   
  17. end  

Output:

Ruby rangers 2

Ranges as Conditions

Ranges are also defined as conditional expressions. Different conditions are defined in a set of lines. These conditions are enclosed within start statement and end statement.

Example:


  1. #!/usr/bin/ruby   
  2. budget = 50000   
  3.   
  4. watch = case budget   
  5.    when 100..1000 then "Local"   
  6.    when 1000..10000 then "Titan"   
  7.    when 5000..30000 then "Fossil"   
  8.    when 30000..100000 then "Rolex"   
  9.    else "No stock"   
  10. end   
  11.   
  12. puts watch

Output:

Ruby rangers 3

Ranges as Intervals

Ranges can also be defined in terms of intervals. Intervals are represented by === case equality operator.

Example:

#!/usr/bin/ruby   

if (('a'..'z') === 'v')   

  puts "v lies in the above range"   

end   

  

if (('50'..'90') === 99)   

  puts "z lies in the above range"   

end

Output:

Ruby rangers 4

Ruby Reverse Range

Ruby reverse range operator does not return any value. If left side value is larger than right side value in a range, no vlaue will be returned.

Example:


  1. #!/usr/bin/ruby   
  2.     puts (5..1).to_a  

Nothing will be returned in the output for the above example.

To print a reverse order, you can use reverse method in a normal range as shown below.

Example:

#!/usr/bin/ruby   

    puts (1..5).to_a.reverse

Output:

Ruby rangers 5

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *