Home » Ruby programming

Array.reverse_each Method with Example in Ruby

Ruby Array.reverse_each Method: Here, we are going to learn about the Array.reverse_each method with example in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on December 22, 2019

Ruby Array.reverse_each Method

In the last article, we have gone through the use of the Array.each method. You must remember that Array.each method is used to traverse the Array from the first element up to the last element and provides no mechanism to process the last element first and the last element in the very end.

To meet this problem with an appropriate solution, we have got Array.reverse_each method. This method, as the name suggests, reverses the element in a certain way. Since this method is non-destructive, this will never reverse the Array. It will only be used to traverse the Array in the reverse order which simply means that we have a facility to fetch the last element of Array instance first and the processing or operation will keep ongoing ever since the first element is not fetched.

Syntax:

    Array.each { |var| #statements}

Parameter(s):

This method does not invite any type of argument or arguments.

Example 1:

=begin
  Ruby program to demonstrate Array.reverse_each
=end

# array declaration
Adc = ['Ruby','Includehelp.com','Ruby','C++','C#','Java','Python','C++','Java']

cnt = 1
Adc.reverse_each do |ele|
	puts "#{cnt} element is #{ele}"
	cnt = cnt + 1
end

Output

1 element is Java
2 element is C++
3 element is Python
4 element is Java
5 element is C#
6 element is C++
7 element is Ruby
8 element is Includehelp.com
9 element is Ruby

Example 2:

=begin
  Ruby program to demonstrate Array.reverse_each
=end

# array declaration
Adc = ['Ruby','Includehelp.com','Ruby','C++','C#','Java','Python','C++','Java']

cnt = 1
Adc.reverse_each {|ele|
	puts "#{cnt} element is #{ele}"
	cnt = cnt + 1
}

Output

1 element is Java
2 element is C++
3 element is Python
4 element is Java
5 element is C#
6 element is C++
7 element is Ruby
8 element is Includehelp.com
9 element is Ruby

Explanation:

In the above two program codes, you can observe that the method named Array.reverse_each can be used in two different ways. Both the ways are quite understandable and their use depends upon your comfort. It is very clear with the help of output that the processing of Array elements starts from the last index and finishes when the first element is being processed. You can never bring any change in the elements of Array with the help of this method because this method is one of the examples of non-destructive methods. This method provides great help when the code requires the processing of the last method first. You can observe that in actual, "Java" is the last element but here it is represented as the very first element.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.