Range class methods in Ruby

RubyServer Side ProgrammingProgramming

Range is a class in Ruby. Ruby ranges represent a set of values that have a beginning and an end. A range can be represented as a number, character, string, or object. A range is constructed with start_point...end_point, start_point...endpoint literals, or with ::new. It provides flexibility and reduces the size of the code.

There are different methods available to us in the range class methods; some of these are class methods whereas some are instance methods. In this article, we will explore both the class methods and the instance methods as well.

The only class method available is the .new one.

new Method

The new method is used to create a range from a given start and end value. In the absence of the third parameter, the range includes the end-object.

Example 1

Consider the code shown below

# new Method

first = 13
second = 17

# Output will be 13..17
puts Range.new(first, second, false)

Output

13..17

All the methods from now on will be instance methods of the range class in Ruby.

begin Method

The begin method is used when we want to return the beginning of a range.

Example 2

Consider the code shown below

# begin method example

# Creating range
myrange = Range.new(4, 8, false)

# begin instance method
puts myrange.begin

Output

4

end Method

The end method is used when we want to return the ending of a range.

Consider the code shown below

Example 3

# end method example

# Creating range
myrange = Range.new(4, 8, false)

# begin instance method
puts myrange.end

Output

8

each Method

The each method is used to iterate over all the elements of the range.

Consider the code shown below

Example 4

# each method example

# using each method
(30..35).each do |itr|
   print itr, '..'
end

Output

30..31..32..33..34..35..
raja
Updated on 25-Jan-2022 11:21:14

Advertisements