From: Robert Klemme Date: 2004-09-20T23:04:45+09:00 Subject: Re: Array#index block and rdetect "trans. (T. Onoma)" schrieb im Newsbeitrag news:200409200947.47623.transami@runbox.com... > On Monday 20 September 2004 08:54 am, Robert Klemme wrote: > > In my understanding Enumerable#each_with_index just goes through the > > enumerable and counts an index which can be used for printing or counting > > or whatever. So I would not change this method. These indexes are purely > > per enumeration and can change for any number of reasons. > > That's an interesting perspective. So you're saying index is just a "helper" > counter. These being equivalent: > > enumobj.each_with_index {|a,i| ... } > > enumobj.each {|a| i=(i||-1)+1; ... } I'd say rather i=-1 enumobj.each {|a| i+=1; ... } Reason: scoping rules: >> %w{aa bb cc}.each {|a| i=(i||-1)+1; p [a,i]} ["aa", 0] ["bb", 0] ["cc", 0] => ["aa", "bb", "cc"] > Maybe so, although I'd prefer #each_with_counter, in that case. Think of an > "index" in the back of a book. Well, there might be better names, but the current name happens to be the one it is. I fear there's enough potential for confusion in that matter so I wouldn't necessarily change that name. > A bit of an aside, I've been thinking about synchronizing enumerable objects. Please be careful with the term "synchronize" - this is usually interpreted in the context of concurrency (multiple threads). > For the sake of discussion lets say *=* means synchronize. So, > > ([1,2,3]*=*[7,8,9]).each {|a,b| puts "#{a},#{b}" } > > => 1,7 > 2,8 > 3,9 > > Then "indexing" can also be done with > > (enumobj*=*(0..enumobj.length-1)).each{|a,i|} > > If a method #range is defined, this can be simplified too > > (enumobj*=*enumobj.range).each{|a,i|} > > Is there a good way to do this? >> [1,2,3].zip [7,8,9] => [[1, 7], [2, 8], [3, 9]] robert