Hi,
Is there a way to access the count / iteration# within an "each" loop? i.e.
how many times through the loop one is?
testhash.each { |d|
puts <count>
}
Tks
Greg
Hi,
Is there a way to access the count / iteration# within an "each" loop? i.e.
how many times through the loop one is?
testhash.each { |d|
puts <count>
}
Tks
Greg
testhash.each_with_index {|d, i| puts i}
- donald
-----Original Message-----
From: Greg Hauptmann [mailto:greg.hauptmann.ruby@gmail.com]
Sent: Friday, June 15, 2007 4:35 PM
To: ruby-talk ML
Subject: accessing the count/iteration # within an "each" ???Hi,
Is there a way to access the count / iteration# within an
"each" loop? i.e.
how many times through the loop one is?testhash.each { |d|
puts <count>}
Greg Hauptmann wrote:
Is there a way to access the count / iteration# within an "each" loop? i.e.
how many times through the loop one is?
ruby$ ri Enumerable#each_with_index
--------------------------------------------- Enumerable#each_with_index
enum.each_with_index {|obj, i| block } -> enum
------------------------------------------------------------------------
Calls block with two arguments, the item and its index, for each
item in enum.
hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
--
RMagick OS X Installer [http://rubyforge.org/projects/rmagick/\]
RMagick Hints & Tips [http://rubyforge.org/forum/forum.php?forum_id=1618\]
RMagick Installation FAQ [http://rmagick.rubyforge.org/install-faq.html\]
excellent - thanks guys
On 6/16/07, Tim Hunter <TimHunter@nc.rr.com> wrote:
Greg Hauptmann wrote:
> Is there a way to access the count / iteration# within an "each"
> loop? i.e.
> how many times through the loop one is?
ruby$ ri Enumerable#each_with_index
--------------------------------------------- Enumerable#each_with_index
enum.each_with_index {|obj, i| block } -> enum
------------------------------------------------------------------------
Calls block with two arguments, the item and its index, for each
item in enum.hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "wombat"=>2, "dog"=>1}--
RMagick OS X Installer [http://rubyforge.org/projects/rmagick/\]
RMagick Hints & Tips [http://rubyforge.org/forum/forum.php?forum_id=1618\]
RMagick Installation FAQ [http://rmagick.rubyforge.org/install-faq.html\]