<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Global Nerdy &#187; each_with_index</title>
	<atom:link href="http://www.globalnerdy.com/tag/each_with_index/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.globalnerdy.com</link>
	<description>Tech Evangelist Joey deVilla on Shopify, startups, software development, tech news and other nerdy stuff</description>
	<lastBuildDate>Thu, 09 Feb 2012 18:30:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Enumerating Enumerable: Enumerable#each_with_index</title>
		<link>http://www.globalnerdy.com/2008/08/01/enumerating-enumerable-enumerableeach_with_index/</link>
		<comments>http://www.globalnerdy.com/2008/08/01/enumerating-enumerable-enumerableeach_with_index/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 04:00:27 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[each_with_index]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1946</guid>
		<description><![CDATA[Here&#8217;s number 11 in the Enumerating Enumerable series, in which I&#8217;m trying to outdo RubyDoc.org in their documentation of Ruby&#8217;s key Enumerable module. In this article, I cover the each_with_index method. In case you missed the earlier articles, they&#8217;re listed and linked below: all? any? collect / map count cycle detect / find drop drop_while [...]]]></description>
			<content:encoded><![CDATA[<p></p><p class="center"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="Enumerating Enumerable" title="enumerating_enumerable" width="350" height="120" /></p>
<p>Here&#8217;s number 11 in the <strong><cite>Enumerating Enumerable</cite></strong> series, in which I&#8217;m trying to outdo RubyDoc.org in their documentation of Ruby&#8217;s key <code>Enumerable</code> module. In this article, I cover the <code>each_with_index</code> method.</p>
<p>In case you missed the earlier articles, they&#8217;re listed and linked below:</p>
<ol>
<li><a href="http://globalnerdy.com/2008/06/23/enumerating-enumerable-enumerableall/">all?</a></li>
<li><a href="http://globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/">any?</a></li>
<li><a href="http://globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/">collect / map</a></li>
<li><a href="http://globalnerdy.com/2008/07/02/enumerating-enumerable-enumerablecount/">count</a></li>
<li><a href="http://globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/">cycle</a></li>
<li><a href="http://globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/">detect / find</a></li>
<li><a href="http://globalnerdy.com/2008/07/10/enumerating-enumerable-enumerabledrop/">drop</a></li>
<li><a href="http://globalnerdy.com/2008/07/25/enumerating-enumerable-enumerabledrop_while/">drop_while</a></li>
<li><a href="http://globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/">each_cons</a></li>
<li><a href="http://www.globalnerdy.com/2008/07/29/enumerating-enumerable-enumerableeach_slice/">each_slice</a></li>
</ol>
<h3>Enumerable#each_with_index Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerableeach_with_index.jpg" alt="Graphic representation of the \&quot;each_with_index\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" title="Graphic representation of the \&quot;each_with_index\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" width="325" height="481" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Think of <code>each_with_index</code> as a version of <code>each</code> that includes an extra piece of information: a number representing the current iteration&#8217;s element&#8217;s position in the collection.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.8 and 1.9</td>
</tr>
<tr>
<th>Expects</th>
<td>An optional block to receive the values from each iteration.</td>
</tr>
<tr>
<th>Returns</th>
<td>
<ul>
<li>The original collection, if used with a block.</li>
<li>An <code>Enumerator</code> object that outputs the collection&#8217;s items and indexes, if used without a block.</li>
</ul>
</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core-1.9/classes/Enumerable.html#M002988">Enumerable#each_with_index</a></td>
</tr>
</table>
<h3>Enumerable#each_with_index and Arrays</h3>
<p>When used with on an array and given a block, <code>each_with_index</code> iterates through the array, passing each item in the array and the number representing its order in the array to the block. Once again, I&#8217;ll use the &#8220;Justice League&#8221; example:</p>
<p><code>
<pre>
justice_league = ["Aquaman", "Batman", "Black Canary", \
                  "Flash", "Green Arrow", "Green Lantern", \
                  "Martian Manhunter", "Superman", \
                  "Vixen", "Wonder Woman"]
justice_league = ["Aquaman", "Batman", "Black Canary", "Flash", "Green Arrow",
"Green Lantern", "Martian Manhunter", "Superman", "Vixen", "Wonder Woman"]

justice_league.each_with_index {|member, index| puts "#{index}: #{member}"}
=> 0: Aquaman
1: Batman
2: Black Canary
3: Flash
4: Green Arrow
5: Green Lantern
6: Martian Manhunter
7: Superman
8: Vixen
9: Wonder Woman
=> ["Aquaman", "Batman", "Black Canary", "Flash", "Green Arrow", "Green Lantern",
"Martian Manhunter", "Superman", "Vixen", "Wonder Woman"]
</pre>
<p></code></p>
<p>Note that unlike the <code>each_cons</code> and <code>each_slice</code>, <code>each_with_index</code> <em>doesn&#8217;t</em> return <code>nil</code>, but the original array, just like <code>each</code> does. <code>each_cons</code> and <code>each_slice</code> are newer methods that were introduced in Ruby 1.9; perhaps Matz and company decided that it made more sense for &#8220;each&#8221; methods to return <code>nil</code> from now on. <code>each</code> and <code>each_with_index</code> have return the original array as they always have, since making changes to these methods might break a lot of existing Ruby code. Hooray for those little inconsistencies that creep into every programming language!</p>
<h3>Enumerable#each_with_index and Hashes</h3>
<p>When used with on a hash and given a block, <code>each_with_index</code> iterates through the hash, converting each item in the hash into a two-element array (where the first element is the key and the second element is the corresponding value), and then passing that array and the number representing its order in the original array to the block. Once again, I&#8217;ll use the &#8220;Enterprise Crew&#8221; example:</p>
<p><code>
<pre>
enterprise_crew = {:captain => "Picard",
                   :first_officer => "Riker",
                   :science_officer => "Data",
                   :tactical_officer => "Worf",
                   :chief_engineer => "LaForge",
                   :chief_medical_officer => "Crusher",
                   :ships_counselor => "Troi",
                   :annoying_ensign => "Crusher",
                   :attractive_ensign => "Ro",
                   :expendable_crew_member => "Smith"}
=> {:captain=>"Picard", :first_officer=>"Riker", :science_officer=>"Data",
:tactical_officer=>"Worf", :chief_engineer=>"LaForge",
:chief_medical_officer=>"Crusher", :ships_counselor=>"Troi",
:annoying_ensign=>"Crusher", :attractive_ensign=>"Ro",
:expendable_crew_member=>"Smith"}

enterprise_crew.each_with_index {|member, index| puts "#{index}: #{member}"}
=> 0: [:captain, "Picard"]
1: [:first_officer, "Riker"]
2: [:science_officer, "Data"]
3: [:tactical_officer, "Worf"]
4: [:chief_engineer, "LaForge"]
5: [:chief_medical_officer, "Crusher"]
6: [:ships_counselor, "Troi"]
7: [:annoying_ensign, "Crusher"]
8: [:attractive_ensign, "Ro"]
9: [:expendable_crew_member, "Smith"]
=> {:captain=>"Picard", :first_officer=>"Riker", :science_officer=>"Data",
:tactical_officer=>"Worf", :chief_engineer=>"LaForge",
:chief_medical_officer=>"Crusher", :ships_counselor=>"Troi",
:annoying_ensign=>"Crusher", :attractive_ensign=>"Ro",
:expendable_crew_member=>"Smith"}
</pre>
<p></code></p>
<h3>Enumerable#each_with_index Oddities</h3>
<h4>Blocks with a Single Parameter</h4>
<p>What happens if you use <code>each_with_index</code> with a block that has only one parameter? You&#8217;d think that the block would accept the item and index passed to it as a two-element array, with the item as the first element and the corresponding index as the second element, but that&#8217;s not the case:</p>
<p><code>
<pre>
# For each item in justice_league, this line will output the following:
# {second letter of member's name} : {first letter of member's name}
justice_league.each_with_index {|member| puts "#{member[1]}: #{member[0]}"}
=> q: A
a: B
l: B
l: F
r: G
r: G
a: M
u: S
i: V
o: W
=> ["Aquaman", "Batman", "Black Canary", "Flash", "Green Arrow", "Green Lantern"
, "Martian Manhunter", "Superman", "Vixen", "Wonder Woman"]
</pre>
<p></code></p>
<p>When <code>each_with_index</code> passes an item and its index to a block that takes only one parameter, the item goes into the paramter, and the index is discarded. Simply put, in this case, <code>each_with_index</code> behaves just like <code>each</code>.</p>
<h4>Without a Block</h4>
<p>What happens if you use <code>each_with_index</code> without a block to create an <code>Enumerator</code> object that spits out the next item when its <code>next</code> method is called? This:</p>
<p><code>
<pre>
hero = justice_league.each_with_index
=> #&lt;Enumerable::Enumerator:0x159cb98&gt;

hero.next
=> "Aquaman"

hero.next
=> "Batman"

hero.next
=> "Black Canary"
</pre>
<p></code></p>
<p>Note that calling <code>next</code> only yields the next item in the collection; the index information is lost. In this case, <code>each_with_index</code> behaves just like <code>each</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/01/enumerating-enumerable-enumerableeach_with_index/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

