Find an Online Tutor Now

Asked • 03/18/19

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| end array.each array.each_index for i in arrayHashes 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?

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.