Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




RUBY - RANGES


Say, for example, you want to find if a number, say 6, is present in the range of numbers from, 1 to 10.


Well! This range of numbers, say 1 to 10, can be represented in Ruby using Double dots '..'.


Let's say we want the numbers from 1 to 10 be in an Array.


It can be achieved very easily using the range i.e. '..'.


Example :



x = 1..10
my_array = x.to_a
puts "The array is :: #{my_array}"


Output :



  The array is :: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

So, in the above example, we taken the range of numbers from 1 to 10 using the range i.e. '..'.


x = 1..10

And initialised the range to a variable x.


Then we have used the to_a method to convert the range of numbers (i.e. In variable x) to an array.


my_array = x.to_a

And initialised the array to a variable my_array.


And when we print the contents of the array, my_array,


puts "The array is :: #{my_array}"

We can see that the range of numbers from 1 to 10 got placed into the array.


The array is :: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Next, let us see the various methods that can be used with Ranges.


Methods to check for the max and min values in the Range.


Example :



x = 1..10
y = x.min
z = x.max
puts "The minimum value is :: #{y}"
puts "The maximum value is :: #{z}"


Output :



  The minimum value is :: 1
  The maximum value is :: 10

So, the above code is self explanatory.


The min method is used to find the minimum value from the array.


y = x.min

And the max method is used to find the maximum value from the array.


y = x.max

Also ranges can be used as conditional statements.


Say, we want to check, if a value lies in the range or not. It can be achieved by the below way,


Example :



x = 1..10
if (x === 6)
   puts "6 is present in the range"
end


Output :



  6 is present in the range

So, in the above code, we have a range from 1 to 10.


x = 1..10

Then we have used the case equality operator === to check if the value, 6 lies in the range or not.


if (x === 6)
	puts "6 is present in the range"
end

And the value 6 lies in the range. So the below output is printed.


6 is present in the range