Ruby Ranges

Range is subset of values pairs of a similar type of objects. This pair elements are based on a decide value of beginning and ending. There are two variant are available in ruby programming.

start..end #fixed, 1 to N
start...end #fixed, 1 to N-1

Start and end are in form of integer, float , string and an object's. Let's seen an example.

spectrum = "a".."e" #Range a to e
numbers = 1...5  # 1 to 4
counting = 1.0..1.5 #1.0 to 1.5

puts spectrum.class

#getting the starting and ending limit
puts spectrum.min
puts spectrum.max

#Check given value are include in Range
puts numbers.include?(6)

puts counting.include?(1.26)

Example of Range in Ruby

Everything in ruby are is an object's. In this example are created three different type of range elements. let's enumerate range element.

counter = 0
data = 2..5
  print "#{element}  "
  counter +=1
puts "\nElement : #{counter}  "
2  3  4  5  
Element : 4 

Convert Range to Array

Ranges element are converted into an array in ruby programming by using of to_a() method.

first = (1..5).to_a
second = ('a'..'e').to_a
third = (1.0..1.5).step(0.100).to_a
p first
p second
p third
Convert range to array in Ruby
[1, 2, 3, 4, 5]
["a", "b", "c", "d", "e"]
[1.0, 1.1, 1.2, 1.3, 1.4, 1.5]

In this last case case when convert floating numbers ranges into an array there are need to provide interval that be a step which is indicate the distance of previous and next iteration. Here use step(0.100).

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment

© 2021,, All rights reserved