What is the “right” way to iterate through an array in 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|



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?


This will iterate through all the elements:

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



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}" }


A => 0
B => 1
C => 2

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

Need Your Help

Telerik RadListView inside asp.net update panel does not refresh

c# asp.net telerik updatepanel radlistview

I've been banging my head against the wall for the last couple of days trying to get this scenario to work.

Bad Image Exception while loading SQLite DLL

c# .net sqlite dll runtime-error

I have a project that is build on Any CPU configuration, .Net Framework 2.0, vs2008 with 32bit version of SQLite dll used in it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.