Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an array starting from the last element? (Ruby)

I came with below solution but I believe that must be nicer one out there ...

array = [ 'first','middle','last']  index = array.length array.length.times { index -= 1; puts array[index]} 
like image 996
Radek Avatar asked Feb 27 '10 03:02

Radek


People also ask

How do I iterate through an array of items in Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

How do you find the last element of an array in Ruby?

Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .

How do you iterate through an array of elements?

In JavaScript, you'll often need to iterate through an array collection and execute a callback method for each iteration. And there's a helpful method JS devs typically use to do this: the forEach() method. The forEach() method calls a specified callback function once for every element it iterates over inside an array.

Which of the following iterator returns all the elements of an array or hash?

Ruby iterators return all the elements of a collection one after another.


2 Answers

Ruby is smart

a = [ "a", "b", "c" ] a.reverse_each {|x| print x, " " } 
like image 193
allenwei Avatar answered Sep 19 '22 17:09

allenwei


array.reverse.each { |x| puts x } 
like image 32
ennuikiller Avatar answered Sep 18 '22 17:09

ennuikiller