Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "right" way to iterate through an array in Ruby?

Tags:

arrays

loops

ruby

PHP, for all its warts, is pretty good on this count. There's no difference between an array and a hash (maybe I'm naive, but this seems obviously right to me), and to iterate through either you just do

foreach (array/hash as $key => $value) 

In Ruby there are a bunch of ways to do this sort of thing:

array.length.times do |i| end  array.each  array.each_index  for i in array 

Hashes make more sense, since I just always use

hash.each do |key, value| 

Why can't I do this for arrays? If I want to remember just one method, I guess I can use each_index (since it makes both the index and value available), but it's annoying to have to do array[index] instead of just value.


Oh right, I forgot about array.each_with_index. However, this one sucks because it goes |value, key| and hash.each goes |key, value|! Is this not insane?

like image 917
Tom Lehman Avatar asked Nov 22 '08 00:11

Tom Lehman


People also ask

How do you iterate an array 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.

What is iterating in Ruby?

“Iterators” is the object-oriented concept in Ruby. In more simple words, iterators are the methods which are supported by collections(Arrays, Hashes etc.). Collections are the objects which store a group of data members. Ruby iterators return all the elements of a collection one after another.

How does array work in Ruby?

Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them.


1 Answers

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6] array.each { |x| puts x }  # Output:  1 2 3 4 5 6 

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"] array.each_with_index {|val, index| puts "#{val} => #{index}" }  # Output:  A => 0 B => 1 C => 2 

I'm not quite sure from your question which one you are looking for.

like image 91
Robert Gamble Avatar answered Sep 16 '22 14:09

Robert Gamble