From: Mayank Kohaley Date: 2011-07-17T23:19:21+09:00 Subject: Re: Array#each vs. Array#each_index iteration --0016e6407caa88184204a844919b Content-Type: text/plain; charset=UTF-8 The documentation clearly says that index method will return the index of the first match so it's not an issue with each, it's the way index method has been designed to work. http://ruby-doc.org/core/classes/Array.html#M000237 Thanks, Mayank Kohaley On Sun, Jul 17, 2011 at 7:40 PM, jake kaiden wrote: > hey folks, > > came across (what i consider) a strange difference between iterating > through an array with #each and #each_index - maybe someone can explain > this? > > i'm working on a baseball scorecard, that splits a string up into an > array, and then searches for keywords like "out," "single," "homer," > etc. here's a simplified example that demonstrates what is confusing to > me: > > ##### > string = "Joe struck out looking blah blah Bill out at second blah blah" > array = string.split > > array.each{|entry| > p array.index(entry) if entry == "out" > } > puts > array.each_index{|index| > p index if array[index] == "out" > } > ##### > > i expected both ways of iterating through the array to give the same > results (2 and 7,) but they don't - what's returned is: > > => 2 > => 2 > > => 2 > => 7 > > why the heck does #each return 2 twice, instead of returning 2 and 7 > like #each_index does? am i missing something obvious here? thanks in > advance for any help... > > - j > > -- > Posted via http://www.ruby-forum.com/. > > --0016e6407caa88184204a844919b--