<?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; enumerable</title>
	<atom:link href="http://www.globalnerdy.com/tag/enumerable/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.globalnerdy.com</link>
	<description>Tech Evangelist Joey deVilla on software development, tech news and other nerdy stuff</description>
	<lastBuildDate>Thu, 19 Nov 2009 02:16:42 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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
each_cons
each_slice

Enumerable#each_with_index Quick Summary



In the simplest possible terms
Think of each_with_index as [...]]]></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>
		<item>
		<title>Enumerating Enumerable: Enumerable#each_slice</title>
		<link>http://www.globalnerdy.com/2008/07/29/enumerating-enumerable-enumerableeach_slice/</link>
		<comments>http://www.globalnerdy.com/2008/07/29/enumerating-enumerable-enumerableeach_slice/#comments</comments>
		<pubDate>Tue, 29 Jul 2008 05:23:48 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[each_slice]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1938</guid>
		<description><![CDATA[<p style="text-align: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>Ten installments already? That's right, this is the tenth <strong><cite>Enumerating Enumerable</cite></strong> article. As I'm fond of repeating, this is my little contribution to the Ruby community: a series of articles where I attempt to do a better job at documenting Ruby's <code>Enumerable</code> module than <a href="http://www.ruby-doc.org/core-1.9/classes/Enumerable.html">Ruby-Doc.org does</a>, with pretty pictures and more in-depth examples!</p>

<p>In this article, I'm going to cover <code>each_slice</code>, which got introduced in Ruby 1.9.</p>

<p style="text-align:center;"><a href="http://globalnerdy.com/2008/07/29/enumerating-enumerable-enumerableeach_slice/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerableeach_slice.jpg" alt="Graphic representation of the &#34;each_slice&#34; method in Ruby&#039;s &#34;Enumerable&#34; module" title="Graphic representation of the &#34;each_slice&#34; method in Ruby&#039;s &#34;Enumerable&#34; module" width="325" height="371" /></a></p>

<p>If you missed any of the earlier articles, I've listed them all 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>
</ol>

<p><a href="http://globalnerdy.com/2008/07/29/enumerating-enumerable-enumerableeach_slice/"><strong>Read on for more...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align: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>Ten installments already? That&#8217;s right, this is the tenth <strong><cite>Enumerating Enumerable</cite></strong> article. As I&#8217;m fond of repeating, this is my little contribution to the Ruby community: a series of articles where I attempt to do a better job at documenting Ruby&#8217;s <code>Enumerable</code> module than <a href="http://www.ruby-doc.org/core-1.9/classes/Enumerable.html">Ruby-Doc.org does</a>, with pretty pictures and more in-depth examples!</p>
<p>In this article, I&#8217;m going to cover <code>each_slice</code>, which got introduced in Ruby 1.9.</p>
<p>If you missed any of the earlier articles, I&#8217;ve listed them all 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>
</ol>
<h3>Enumerable#each_slice Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerableeach_slice_2.jpg" alt="Graphic representation of the &quot;each_slice&quot; method in Ruby&#039;s &quot;Enumerable&quot; module" title="Graphic representation of the &quot;each_slice&quot; method in Ruby&#039;s &quot;Enumerable&quot; module" width="415" height="367" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Given a number <i>n</i>, split the array into <i>n</i>-element slices (if the number of elements in the array isn&#8217;t evenly divisible by <i>n</i>, just put the remaining elements in the last slice), then iterate through those slices.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>
<ul>
<li>A number <i>n</i> describing the size of the iteration slice.</li>
<li>An optional block to receive the values from each iteration.</li>
</ul>
</td>
</tr>
<tr>
<th>Returns</th>
<td>
<ul>
<li><code>nil</code>, if used with a block.</li>
<li>An <code>Enumerator</code> object that outputs <i>n</i>-sized slices of the collection, 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#M002955">Enumerable#each_slice</a></td>
</tr>
</table>
<h3>Enumerable#each_slice and Arrays</h3>
<p>When used on an array with a block, <code>each_slice</code> takes a numeric argument <i>n</i> and splits the array into slices of length <i>n</i> (if the number of elements in the array isn&#8217;t evenly divisible by <i>n</i>, the remaining elements are put into the last slice). <code>each_slice</code> then iterates through the set of slices, passing each slice to the block. After the final iteration, <code>each_slice</code> returns <code>nil</code>.</p>
<p>Since this is yet another case when an showing an example makes things very clear, I&#8217;ll do just that, using the same example data I used in <a href="http://globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/">the article on <code>each_cons</code></a>:</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_slice(3) {|team| p team}
=> ["Aquaman", "Batman", "Black Canary"]
["Flash", "Green Arrow", "Green Lantern"]
["Martian Manhunter", "Superman", "Vixen"]
["Wonder Woman"]
=> nil
</pre>
<p></code></p>
<p>When used on an array without a block, <code>each_slice</code> takes a numeric argument <i>n</i> and returns an <code>Enumerator</code> that outputs slices of the array when its <code>next</code> method is called. Here&#8217;s an example:</p>
<p><code>
<pre>
teams_of_3 = justice_league.each_slice(3)
=> #&lt;Enumerable::Enumerator:0x007fc73baa9830&gt;

teams_of_3.next
=> ["Aquaman", "Batman", "Black Canary"]

teams_of_3.next
=> ["Flash", "Green Arrow", "Green Lantern"]

teams_of_3.next
=> ["Martian Manhunter", "Superman", "Vixen"]

teams_of_3.next
=> ["Wonder Woman"]

teams_of_3.next
=> StopIteration: iteration reached at end...
# (I'm skipping the rest of the error message)

teams_of_3.rewind
=> #&lt;Enumerable::Enumerator:0x007fc73baa9830&gt;

teams_of_3.next
=> ["Aquaman", "Batman", "Black Canary"]
</pre>
<p></code></p>
<h3>Enumerable#each_slice and Hashes</h3>
<p>When used on an hash with a block, <code>each_slice</code> takes a numeric argument <i>n</i> and splits the hash into arrays of length <i>n</i> (if the number of elements in the array isn&#8217;t evenly divisible by <i>n</i>, the remaining elements are put into the last slice). Within these arrays, each hash element is represented as a two-element array, with the first element being the key and the second element being the corresponding value.</p>
<p><code>each_slice</code> then iterates through the set of arrays, passing each array to the block. After the final iteration, <code>each_slice</code> returns <code>nil</code>.</p>
<p>Here&#8217;s an example, using the same example data I used in <a href="http://globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/">the article on <code>each_cons</code></a>:</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"}
=> nil

enterprise_crew.each_slice(3) {|team| p team}
=> [[: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"]]
=> nil
</pre>
<p></code></p>
<p>When used on a hash without a block, <code>each_slice</code> takes a numeric argument <i>n</i> and returns an <code>Enumerator</code> that outputs arrays when its <code>next</code> method is called. Here&#8217;s an example:</p>
<p><code>
<pre>
away_teams_of_3 = enterprise_crew.each_slice(3)
=> #&lt;Enumerable::Enumerator:0x007fc73ba44c50&gt;

away_teams_of_3.next
=> [[:captain, "Picard"], [:first_officer, "Riker"], [:science_officer, "Data"]]

away_teams_of_3.next
=> [[:tactical_officer, "Worf"], [:chief_engineer, "LaForge"], [:chief_medical_officer, "Crusher"]]

away_teams_of_3.next
=> [[:ships_counselor, "Troi"], [:annoying_ensign, "Crusher"], [:attractive_ensign, "Ro"]]

away_teams_of_3.next
=> [[:expendable_crew_member, "Smith"]]

away_teams_of_3.next
=> StopIteration: iteration reached at end...
# (I'm skipping the rest of the error message)

away_teams_of_3.rewind
=> #<Enumerable::Enumerator:0x007fc73ba44c50>

away_teams_of_3.next
=> [[:captain, "Picard"], [:first_officer, "Riker"], [:science_officer, "Data"]]
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/29/enumerating-enumerable-enumerableeach_slice/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#each_cons</title>
		<link>http://www.globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/</link>
		<comments>http://www.globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/#comments</comments>
		<pubDate>Mon, 28 Jul 2008 04:00:40 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[each_cons]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1918</guid>
		<description><![CDATA[<p style="text-align: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>Welcome to the ninth installment of <cite>Enumerating Enumerable</cite>, the series of articles where I attempt to do a better job at documenting Ruby's <code>Enumerable</code> module than Ruby-Doc.org does.</p>

<p>I'm going through the <code>Enumerable</code>'s methods in alphabetical order, and we've reached the methods that are variations on <code>each</code> In this article, I'm going to cover <code>each_cons</code>, which got introduced in Ruby 1.9.</p>

<p>If you missed any of the earlier articles, I've listed them all 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>
</ol>

<p><a href="http://globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/"><strong>Read on for more...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align: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>Welcome to the ninth installment of <cite>Enumerating Enumerable</cite>, the series of articles where I attempt to do a better job at documenting Ruby&#8217;s <code>Enumerable</code> module than Ruby-Doc.org does.</p>
<p>I&#8217;m going through the <code>Enumerable</code>&#8217;s methods in alphabetical order, and we&#8217;ve reached the methods that are variations on <code>each</code> In this article, I&#8217;m going to cover <code>each_cons</code>, which got introduced in Ruby 1.9.</p>
<p>If you missed any of the earlier articles, I&#8217;ve listed them all 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>
</ol>
<h3>Enumerable#each_cons Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerableeach_cons_2.jpg" alt="Graphic representation of the \&quot;each_cons\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" title="Graphic representation of the \&quot;each_cons\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" width="415" height="486" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Think of <code>each_cons</code> as an <code>each</code> that takes a number <em>n</em> and spits out <em>n</em> elements at a time.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>A number <em>n</em> describing the number of elements to be fed to the block.</td>
</tr>
<tr>
<th>Returns</th>
<td>
<ul>
<li><code>nil</code> if used with a block</li>
<li>An <code>Enumerator</code> object that outputs <em>n</em>-sized consecutive array slices of the collection 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#M002956">Enumerable#each+cons</a></td>
</tr>
</table>
<h3>Enumerable#each_cons and Arrays</h3>
<p>When used on an array and given a block and a number <em>n</em> as an argument, <code>each_cons</code> is like an <code>each</code> that goes through each element in the array and outputs an <em>n</em>-sized array slice of the original array starting at the current element.</p>
<p><code>each_cons</code> is one of those methods that&#8217;s really tough to describe. This is one of those cases where a demonstrating trumps describing&#8230;</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_cons(3) {|team| p team}
=> ["Aquaman", "Batman", "Black Canary"]
["Batman", "Black Canary", "Flash"]
["Black Canary", "Flash", "Green Arrow"]
["Flash", "Green Arrow", "Green Lantern"]
["Green Arrow", "Green Lantern", "Martian Manhunter"]
["Green Lantern", "Martian Manhunter", "Superman"]
["Martian Manhunter", "Superman", "Vixen"]
["Superman", "Vixen", "Wonder Woman"]
=> nil
</pre>
<p></code></p>
<p>Note that in this case, <code>each_cons</code> returns <code>nil</code>.</p>
<p><code>each_cons</code> can also be used without providing a block. In this case, you&#8217;re using it to create an <code>Enumerator</code> object that you can then use to spit out array slices when you call its <code>next</code> method:</p>
<p><code>
<pre>
# Let's create an enumerator that we can use to give us three-person
# superhero teams
teams_of_3 = justice_league.each_cons(3)
=> #<enumerable::Enumerator:0x007f8f83ecc538>

# Let's get the first team of 3
teams_of_3.next
=> ["Aquaman", "Batman", "Black Canary"]

# Now the next one...
teams_of_3.next
=> ["Batman", "Black Canary", "Flash"]

teams_of_3.next
=> ["Black Canary", "Flash", "Green Arrow"]

teams_of_3.next
=> ["Flash", "Green Arrow", "Green Lantern"]

# Let's go back to the first team of 3
teams_of_3.rewind
=> #<enumerable::Enumerator:0x007f8f83ecc538>

teams_of_3.next
=> ["Aquaman", "Batman", "Black Canary"]
</pre>
<p></code></p>
<h3>Enumerable#each_cons and Hashes</h3>
<p>When used on a hash and given a block and a number <em>n</em> as an argument, <code>each_cons</code> is like an <code>each</code> that goes through each element in the array and outputs an <em>n</em>-sized array slice of the hash starting at the current element. Note that in the process, hash elements are converted into two-element arrays where the first element contains the key and the second element contains the corresponding value.</p>
<p>Again, examples speak louder than descriptions:</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", :tact
ical_officer=>"Worf", :chief_engineer=>"LaForge", :chief_medical_officer=>"Crush
er", :ships_counselor=>"Troi", :annoying_ensign=>"Crusher", :attractive_ensign=>
"Ro", :expendable_crew_member=>"Smith"}

enterprise_crew.each_cons(3) {|team| p team}
=> [[:captain, "Picard"], [:first_officer, "Riker"], [:science_officer, "Data"]]
[[:first_officer, "Riker"], [:science_officer, "Data"], [:tactical_officer, "Worf"]]
[[:science_officer, "Data"], [:tactical_officer, "Worf"], [:chief_engineer, "LaForge"]]
[[:tactical_officer, "Worf"], [:chief_engineer, "LaForge"], [:chief_medical_officer, "Crusher"]]
[[:chief_engineer, "LaForge"], [:chief_medical_officer, "Crusher"], [:ships_counselor, "Troi"]]
[[:chief_medical_officer, "Crusher"], [:ships_counselor, "Troi"], [:annoying_ensign, "Crusher"]]
[[:ships_counselor, "Troi"], [:annoying_ensign, "Crusher"], [:attractive_ensign, "Ro"]]
[[:annoying_ensign, "Crusher"], [:attractive_ensign, "Ro"], [:expendable_crew_member, "Smith"]]
=> nil
</pre>
<p></code></p>
<p>As with arrays, <code>each_cons</code>, when used on a hash, returns <code>nil</code>.</p>
<p>Again, as with arrays, <code>each_cons</code> can also be used without providing a block to create an <code>Enumerator</code>:</p>
<p><code>
<pre>
# Starfleet has decided to let the ship's computer determine
# the away teams, which are groups of 3
away_teams_of_3 = enterprise_crew.each_cons(3)
=> #<enumerable::Enumerator:0x007f8f83ee82b0>

# Okay, who's the first away team?
away_teams_of_3.next
=> [[:captain, "Picard"], [:first_officer, "Riker"], [:science_officer, "Data"]]

# Let's get the next one
away_teams_of_3.next
=> [[:first_officer, "Riker"], [:science_officer, "Data"],
[:tactical_officer, "Worf"]]

away_teams_of_3.next
=> [[:science_officer, "Data"], [:tactical_officer, "Worf"],
[:chief_engineer, "LaForge"]]

# Let's go back to the first away team
away_teams_of_3.rewind
=> #<enumerable::Enumerator:0x007f8f83ee82b0>

away_teams_of_3.next
=> [[:captain, "Picard"], [:first_officer, "Riker"], [:science_officer, "Data"]]
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/28/enumerating-enumerable-enumerableeach_cons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#drop_while</title>
		<link>http://www.globalnerdy.com/2008/07/25/enumerating-enumerable-enumerabledrop_while/</link>
		<comments>http://www.globalnerdy.com/2008/07/25/enumerating-enumerable-enumerabledrop_while/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 02:28:26 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[drop_while]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1773</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p>After the wackiness of the past couple of weeks -- some travel to see family, followed by <a href="http://globalnerdy.com/2008/07/14/this-week-in-toronto-tech/">a busy week of tech events including DemoCamp 18, Damian Conway's presentation, FAILCamp and RubyFringe</a> -- I'm happy to return to <cite>Enumerating Enumerable</cite>, the article series in which I attempt to do a better job at documenting Ruby's <code>Enumerable</code> module than Ruby-Doc.org does.</p>

<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerabledrop_while.jpg" alt="Graphic representation of the \&#34;drop_while\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; module" title="Graphic representation of the \&#34;drop_while\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; module" width="257" height="251" class="size-full wp-image-1890" /></p>

<p>In this article, the eighth in the series, I'm going to cover a method introduced in Ruby 1.9: <code>drop_while</code>.</p>

<p>I'm going through the <code>Enumerable</code>'s methods in alphabetical order. If you missed any of the earlier articles, I've listed them all 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>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p>After the wackiness of the past couple of weeks &#8212; some travel to see family, followed by <a href="http://globalnerdy.com/2008/07/14/this-week-in-toronto-tech/">a busy week of tech events including DemoCamp 18, Damian Conway&#8217;s presentation, FAILCamp and RubyFringe</a> &#8212; I&#8217;m happy to return to <cite>Enumerating Enumerable</cite>, the article series in which I attempt to do a better job at documenting Ruby&#8217;s <code>Enumerable</code> module than Ruby-Doc.org does.</p>
<p>In this article, the eighth in the series, I&#8217;m going to cover a method introduced in Ruby 1.9: <code>drop_while</code>.</p>
<p>I&#8217;m going through the <code>Enumerable</code>&#8217;s methods in alphabetical order. If you missed any of the earlier articles, I&#8217;ve listed them all 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>
</ol>
<h3>Enumerable#drop_while Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerabledrop_while.jpg" alt="Graphic representation of the \&quot;drop_while\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" title="Graphic representation of the \&quot;drop_while\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" width="257" height="251" class="size-full wp-image-1890" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Given a collection and a condition, return an array made of the collection&#8217;s items, starting the first item that <em>doesn&#8217;t</em> meet the condition.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>A block containing the condition.</td>
</tr>
<tr>
<th>Returns</th>
<td>An array made up of the remaining items, if there are any.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://ruby-doc.org/core/classes/Enumerable.html#M001171">Enumerable#drop_while</a></td>
</tr>
</table>
<h3>Enumerable#drop_while and Arrays</h3>
<p>When used on an array, <code>drop_while</code> returns a copy of the array created by going through the original array&#8217;s items in order, dropping elements until it encounters the an element that <em>does not</em> meet the condition. The resulting array is basically a copy of the original array, starting at the first element that doesn&#8217;t meet the condition in the block.</p>
<p>As in many cases, things become clearer with some examples:</p>
<p><code>
<pre>
# In Canada, and in fact in all but 2 countries in the world,
# the weather report gives temperatures in Celsius!
temperatures = [28, 25, 30, 22, 27]
=> [28, 25, 30, 22, 27]

# The block returns true for the FIRST two elements,
# and false for the third.
# So drop_while returns an array like the original,
# but starting at the third element.
temperatures.drop_while {|temperature| temperature < 30}
=> [30, 22, 27]

# The block returns false for the first element,
# so drop_while returns an array like the original,
# starting at the first element
# (in other words, a copy of the original).
temperatures.drop_while {|temperature| temperature < 28}
=> [28, 25, 30, 22, 27]
</pre>
<p></code></p>
<h3>Enumerable#drop_while and Hashes</h3>
<p>When used on a hash, <code>drop_while</code> effectively:</p>
<ul>
<li>Creates an array based on the hash, with each element in the hash represented as a two-element array where the first element contains the key and the second element containing the corresponding value, then</li>
<li>goes through each element in the array, dropping elements until it encounters the first element that doesn&#8217;t meet the condition in the block. The resulting array is an array of two-element arrays, starting at the first element that doesn&#8217;t meet the condition in the block.</li>
</ul>
<p>Once again, examples will make this all clear:</p>
<p><code>
<pre>
# We're basically taking the array from the previous example
# and dressing it up in a hash
city_temperatures = {"New York" => 28, \
                     "Toronto" => 25, \
                     "Washington" => 30, \
                     "Montreal" => 22, \
                     "Boston" => 27}
=> {"New York"=>28, "Toronto"=>25, "Washington"=>30,
"Montreal"=>22, "Boston"=>27}

# The block returns true for the FIRST two elements,
# and false for the third.
# So drop_while returns an array based on the hash,
# but starting at the third element
# (and, of course, the key-value pairs turned into
# two-element arrays).
city_temperatures.drop_while {|city_temperature| city_temperature[1] < 30}
=> [["Washington", 30], ["Montreal", 22], ["Boston", 27]]

# This is a more readable version of the line above
city_temperatures.drop_while {|city, temperature| temperature < 30}
=> [["Washington", 30], ["Montreal", 22], ["Boston", 27]]

# The block returns false for the first element,
# so drop_while returns an array based on the hash,
# starting at the first element
# (in other words, an array based on the original hash,
# with key-value pairs turned into two-element arrays).
city_temperatures.drop_while {|city,temperature| temperature < 28}
=> [["New York", 28], ["Toronto", 25], ["Washington", 30],
["Montreal", 22], ["Boston", 27]]
</pre>
<p></code></p>
<h3>Enumerable#drop_while&#8217;s Evil Twin, Enumerable#take_while</h3>
<p>I’ll cover <code>take_while</code> in detail in a later installment, but for now, an example should suffice:</p>
<p><code>
<pre>
city_temperatures.drop_while {|city_temperature| city_temperature[1] < 30}
=> [["Washington", 30], ["Montreal", 22], ["Boston", 27]]

city_temperatures.take_while {|city_temperature| city_temperature[1] < 30}
=> [["New York", 28], ["Toronto", 25]]
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/25/enumerating-enumerable-enumerabledrop_while/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#drop</title>
		<link>http://www.globalnerdy.com/2008/07/10/enumerating-enumerable-enumerabledrop/</link>
		<comments>http://www.globalnerdy.com/2008/07/10/enumerating-enumerable-enumerabledrop/#comments</comments>
		<pubDate>Thu, 10 Jul 2008 04:00:42 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[drop]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1770</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p><cite>Enumerating Enumerable</cite> marches on!</p>

<p>This is the seventh article in my series in which I try to do a better job of documenting Ruby's <code>Enumerable</code> module than Ruby-Doc.org does. If you've missed the other articles in the series, they're listed 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>
</ol>

<p style="text-align:center;"><a href="http://globalnerdy.com/2008/07/10/enumerating-enumerable-enumerabledrop/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerabledrop.jpg" alt="Graphic representation of the \&#34;drop\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; module" title="Graphic representation of the \&#34;drop\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; module" width="290" height="253" /></a></p>

<p>In this installment, I cover a method added in Ruby 1.9: <code>drop</code>.</p>

<p><a href="http://globalnerdy.com/2008/07/10/enumerating-enumerable-enumerabledrop/"><strong>Read on for more on <code>Enumerable#drop</code>...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p><cite>Enumerating Enumerable</cite> marches on!</p>
<p>This is the seventh article in my series in which I try to do a better job of documenting Ruby&#8217;s <code>Enumerable</code> module than Ruby-Doc.org does. If you&#8217;ve missed the other articles in the series, they&#8217;re listed 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>
</ol>
<p>In this installment, I cover a method added in Ruby 1.9: <code>drop</code>.</p>
<h3>Enumerable#drop Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerabledrop.jpg" alt="Graphic representation of the \&quot;drop\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" title="Graphic representation of the \&quot;drop\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" width="290" height="253" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Given a collection and a number <em>n</em>, create an array made of the items of the collection with the first <em>n</em> items removed.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>The number of elements to remove from the start of the collection.</td>
</tr>
<tr>
<th>Returns</th>
<td>An array made up of the remaining items, if there are any./td><br />
    </tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://ruby-doc.org/core/classes/Enumerable.html#M001170">Enumerable#drop</a></td>
</tr>
</table>
<h3>Enumerable#drop and Arrays</h3>
<p>With an array, <code>drop</code> takes a number <em>n</em> as an argument and returns an array created by removing the first <em>n</em> elements of the array. The resulting array is made up of the remaining elements.</p>
<p><code>
<pre>
# These are the favourite bands of RubyFringe organizer
# Meghan Katleen Millard's, according to her Facebook profile
meghans_fave_bands = ["Afghan Whigs", "Bjork", "Charles Mingus",
"Deerhunter", "Electrelane", "Francois Hardy", "Godspeed You Black Emperor!"]
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter", "Electrelane",
"Francois Hardy", "Godspeed You Black Emperor!"]

# Let's lose the first 5
meghans_fave_bands.drop 5
=> ["Francois Hardy", "Godspeed You Black Emperor!"]

# The original array is not affected
meghans_fave_bands
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter", "Electrelane",
"Francois Hardy", "Godspeed You Black Emperor!"]
</pre>
<p></code></p>
<h3>Enumerable#drop and Hashes</h3>
<p>With an hash, <code>drop</code> takes a number <em>n</em> as an argument and returns an array created by removing the first <em>n</em> elements of the array (<code>drop</code> is only in Ruby 1.9 and later, where hashes keep the order in which they were defined, so its results are predictable). The resulting array is made up of the remaining elements, with each element converted into a two-element array where element 0 is the key and element 1 is the corresponding value.</p>
<p><code>
<pre>
# Here's a hash of the first five U.S. states
# (in terms of alphabetical order) and their capitals.
# This example is in Ruby 1.9, which means that
# the hash keys will stay in the order in which
# they were defined.
states_and_capitals = {"Alabama" => "Montgomery", \
                       "Alaska"  => "Juneau", \
                       "Arizona" => "Phoenix", \
                       "Arkansas" => "Little Rock", \
                       "California" => "Sacramento"}
=> {"Alabama"=>"Montgomery", "Alaska"=>"Juneau", "Arizona"=>"Phoenix",
"Arkansas"=>"Little Rock", "California"=>"Sacramento"}

# Let's remove the first 3
states_and_capitals.drop 3
=> [["Arkansas", "Little Rock"], ["California", "Sacramento"]]

# The original hash is not affected
states_and_capitals
=> {"Alabama"=>"Montgomery", "Alaska"=>"Juneau", "Arizona"=>"Phoenix",
"Arkansas"=>"Little Rock", "California"=>"Sacramento"}
</pre>
<p></code></p>
<h3>Enumerable#take: Enumerable#drop&#8217;s Evil Twin</h3>
<p>I&#8217;ll cover <code>take</code> in detail in a later installment, but for now, an example should suffice:</p>
<p><code>
<pre>
meghans_fave_bands = ["Afghan Whigs", "Bjork", "Charles Mingus",
"Deerhunter", "Electrelane", "Francois Hardy", "Godspeed You Black Emperor!"]
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter", "Electrelane",
"Francois Hardy", "Godspeed You Black Emperor!"]

# drop(n) removes the first n elements
meghans_fave_bands.drop(4)
=> ["Electrelane", "Francois Hardy", "Godspeed You Black Emperor!"]

meghans_fave_bands.take(4)
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter"]
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/10/enumerating-enumerable-enumerabledrop/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#detect/Enumerable#find</title>
		<link>http://www.globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/</link>
		<comments>http://www.globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 05:02:35 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[detect]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[find]]></category>
		<category><![CDATA[lambdas]]></category>
		<category><![CDATA[procs]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1769</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p>Here's another article in the <cite>Enumerating Enumerable</cite> series, in which I attempt to improve upon <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org's documentation for the <code>Enumerable</code> module</a>, which I find rather lacking. If you've missed the previous articles in the series, I've listed them 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>
</ol>

<p style="text-align:center;"><a href="http://globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerabledetect_enumerablefind.jpg" alt="Graphic representation of the \&#34;detect\&#34; or \&#34;find\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; module." title="Graphic representation of the \&#34;detect\&#34; or \&#34;find\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; module." width="299" height="252" /></a></p>

<p>This installment covers a method that goes by two names: <code>detect</code> or <code>find</code>. I personally prefer <code>find</code>, as it's shorter and the term I tend to use for its function.</p>

<p><a href="http://globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/"><strong>Read on for more about Enumerable#detect/Enumerable#find...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p>Here&#8217;s another article in the <cite>Enumerating Enumerable</cite> series, in which I attempt to improve upon <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org&#8217;s documentation for the <code>Enumerable</code> module</a>, which I find rather lacking. If you&#8217;ve missed the previous articles in the series, I&#8217;ve listed them 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>
</ol>
<p>This installment covers a method that goes by two names: <code>detect</code> or <code>find</code>. I personally prefer <code>find</code>, as it&#8217;s shorter and the term I tend to use for its function.</p>
<h3>Enumerable#detect/Enumerable#find Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerabledetect_enumerablefind.jpg" alt="Graphic representation of the \&quot;detect\&quot; or \&quot;find\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module." title="Graphic representation of the \&quot;detect\&quot; or \&quot;find\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module." width="299" height="252" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>What&#8217;s the first item in the collection that meets the given criteria?</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.8 and 1.9</td>
</tr>
<tr>
<th>Expects</th>
<td>
<ul>
<li>A block containing the criteria.</li>
<li>An optional argument containing a proc that calculates a &#8220;default&#8221; value — that is, the value to return if no item in the collection matches the criteria.</li>
</ul>
</td>
</tr>
<tr>
<th>Returns</th>
<td>The first item in the collection that matches the criteria, if one exists.<br />
If no such item exists in the collection, <code>detect</code>/<code>find</code> returns:
<ul>
<li><code>nil</code> is returned if no argument is provided</li>
<li>the value of the argument, if one is provided.</li>
</ul>
</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://ruby-doc.org/core/classes/Enumerable.html#M001139">Enumerable#detect / Enumerable#find</a></td>
</tr>
</table>
<h3>Enumerable#detect/Enumerable#find and Arrays</h3>
<p>When used on an array without an argument, <code>detect</code>/<code>find</code> passes each item from the collection to the block and&#8230;</p>
<ul>
<li>If the current item causes the block to return a value that doesn&#8217;t evaluate to <code>false</code>, <code>detect</code>/<code>find</code> stops going through collection and returns the item.</li>
<li>If no item in the collection causes the block to return a value that doesn&#8217;t evaluate to <code>false</code>, <code>detect</code>/<code>find</code> returns <code>nil</code>.</li>
</ul>
<p>In the examples that follow, I&#8217;ll be using the <code>find</code> method. <code>detect</code> does exactly the same thing; it&#8217;s just that I prefer <code>find</code>.</p>
<p><code>
<pre>
# Time to establish my "old fart" credentials
classic_rock_bands = ["AC/DC", "Black Sabbath", "Queen", \
"Ted Nugent and the Amboy Dukes", "Scorpions", "Van Halen"]
=> ["AC/DC", "Black Sabbath", "Queen", "Ted Nugent and the Amboy Dukes",
"Scorpions", "Van Halen"]

# Of the bands in the array, which is the first one
# whose name is longer than 8 characters?
classic_rock_bands.find {|band| band.length > 8}
=> "Black Sabbath"

# Which is the first one whose name is exactly
# 5 characters long?
classic_rock_bands.find {|band| band.length == 5}
=> "AC/DC"

# The order of items in the array can affect "find"'s result.
# Let's put the array into reverse sorted order:
classic_rock_bands.sort!.reverse!
=> ["Van Halen", "Ted Nugent and the Amboy Dukes", "Scorpions", \
"Queen", "Black Sabbath", "AC/DC"]

# Again: which is the first band whose name
# is longer than 8 characters?
=> "Van Halen"

# Again: which is the first band whose name
# is exactly 5 characters?
=> "Queen"

# If no band in the array meets the criteria,
# "find" returns nil.
# There are no bands in the list with names shorter
# than 5 characters...
classic_rock_bands.find {|band| band.length < 5}
=> nil
</pre>
<p></code></p>
<p>Using the optional argument is a topic big enough to merit its own section, which appears later in this article.</p>
<h3>Enumerable#detect/Enumerable#find and Hashes</h3>
<p>When used on a hash and a block is provided, <code>detect</code>/<code>find</code> passes each key/value pair in the hash to the block, which you can “catch” as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p>When used on a hash without an argument, <code>detect</code>/<code>find</code> passes each item from the collection to the block and&#8230;</p>
<ul>
<li>If the current item causes the block to return a value that doesn&#8217;t evaluate to <code>false</code>, <code>detect</code>/<code>find</code> stops going through collection and returns the item.</li>
<li>If no item in the collection causes the block to return a value that doesn&#8217;t evaluate to <code>false</code>, <code>detect</code>/<code>find</code> returns <code>nil</code>.</li>
</ul>
<p><code>
<pre>
years_founded = {"AC/DC" => 1973, \
                 "Black Sabbath" => 1968, \
                 "Queen" => 1970, \
                 "Ted Nugent and the Amboy Dukes" => 1967, \
                 "Scorpions" => 1965, \
                 "Van Halen" => 1972}
# Ruby 1.8 re-orders hashes in some mysterious way that is almost never
# the way you entered it. Here's what I got in Ruby 1.8:
=> {"Queen"=>1970, "AC/DC"=>1973, "Black Sabbath"=>1968, "Scorpions"=>1965,
"Ted Nugent and the Amboy Dukes"=>1967, "Van Halen"=>1972}

# Ruby 1.9 preserves hash order so that hashes keep the order in which
# you defined them. Here's what I got in Ruby 1.9:
=> {"AC/DC"=>1973, "Black Sabbath"=>1968, "Queen"=>1970,
"Ted Nugent and the Amboy Dukes"=>1967, "Scorpions"=>1965, "Van Halen"=>1972}

# Which band is the first in the hash to be founded
# in 1970 or later?
years_founded.find {|band| band[1] >= 1970}
# In Ruby 1.8, the result is:
=> ["Queen", 1970]
# In Ruby 1.9, the result is:
=> ["AC/DC", 1973]

# Here's another way of phrasing it:
years_founded.find {|band, year_founded| year_founded >= 1970}
</pre>
<p></code></p>
<h3>Using Enumerable#detect/Enumerable#find with the Optional Argument</h3>
<p><code>detect</code>/<code>find</code>&#8217;s optional argument lets you specify a proc or lambda whose return value will be the result in cases where no object in the collection matches the criteria.</p>
<p>(Unfortunately, a complete discussion of procs and lambdas is beyond the scope of this article. I highly recommend looking at Eli Bendersky&#8217;s very informative article, <a href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/"><cite>Understanding Ruby blocks, Procs and methods</cite></a>.)</p>
<p>I think that the optional argument is best explained through examples&#8230;</p>
<p><code>
<pre>
# Once again, the array of classic rock bands
classic_rock_bands = ["AC/DC", "Black Sabbath", "Queen", \
"Ted Nugent and the Amboy Dukes", "Scorpions", "Van Halen"]

# Let's define a proc that will simply returns the band name
# "ABBA", who are most definitely not considered to be
# a classic rock band.
default_band = Proc.new {"ABBA"}

# Procs are objects, so using a proc's name alone isn't sufficient
to invoke its code -- doing so will simply return the proc object.
default_band
=> #&lt;Proc:0x00553f34@(irb):31&gt;
# (The actual value will be different for you, but you get the idea.)

# To call a proc, you have to use its "call" method:
default_band.call
=> "ABBA"

# What we want to do is use "default_band" as a proc that
# provides a default value in the event that detect/find doesn't
# find a value that matches the critera.

# detect/find calls the "call" method of the object you provide
# as the argument if no item in the collection matches the
# criteria in the block.

# There *is* a band in the array that comes after
# "Led Zeppelin" alphabetically: Queen.
classic_rock_bands.find(default_band) {|band| band > "Led Zeppelin"}
=> "Queen"

# The last band in the array, alphabetically speaking,
# is Van Halen. So if we ask detect/find to find a band that
# comes after Van Halen, it won't find one.
# Without the argument, detect/find returns nil,
# but *with* the argument, it will invoke the "call"
# method of the object you provide it.
classic_rock_bands.find(default_band) {|band| band > "Van Halen"}
=> "ABBA"

# Let's try something a little fancier. This time, we'll use a lambda.
# The differences between procs and lambdas are very fine -- I suggest
# you check Eli Bendersky's article for those differences.

# Let's create a lambda that when called,
# returns the name of a randomly-selected pop singer.
random_band = lambda do
    fallback_bands = ["Britney Spears", "Christina Aguilera", "Ashlee Simpson"]
    fallback_bands[rand(fallback_bands.size)]
end

# Let's give it a try...
classic_rock_bands.find(random_band) {|band| band > "Van Halen"}
=> "Britney Spears"

classic_rock_bands.find(random_band) {|band| band > "Van Halen"}
=> "Ashlee Simpson"

classic_rock_bands.find(random_band) {|band| band > "Van Halen"}
=> "Christina Aguilera"

classic_rock_bands.find(random_band) {|band| band > "Led Zeppelin"}
=> "Queen"
</pre>
<p></code></p>
<p>To see a &#8220;real&#8221; application of <code>detect</code>/<code>find's</code> optional argument, see <a href="http://www.rubyquiz.com/quiz77.html">this <cite>Ruby Quiz</cite> problem.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#cycle</title>
		<link>http://www.globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/</link>
		<comments>http://www.globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/#comments</comments>
		<pubDate>Sun, 06 Jul 2008 04:00:22 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1772</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p>Welcome to another installment of <cite>Enumerating Enumerable</cite>, my series of articles in which I attempt to improve upon <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org's documentation for the <code>Enumerable</code> module.</a> So far, I've covered the following methods in this series:</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>
    </ol>

<p style="text-align:center;"><a href="http://globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerablecycle.jpg" alt="Graphic representation of the \&#34;cycle\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; class." title="Graphic representation of the \&#34;cycle\&#34; method in Ruby\&#039;s \&#34;Enumerable\&#34; class." width="194" height="412" /></a></p>

<p>In this installment, I'm going to cover a method added into <code>Enumerable</code> in Ruby 1.9: <code>Enumerable#cycle</code>. It's particularly poorly-documented in RubyDoc.org, and there isn't much written about it anywhere else.</p>

<p><a href="http://globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/"><strong>Read on for more about Enumerable#cycle...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p>Welcome to another installment of <cite>Enumerating Enumerable</cite>, my series of articles in which I attempt to improve upon <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org&#8217;s documentation for the <code>Enumerable</code> module.</a> So far, I&#8217;ve covered the following methods in this series:</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>
</ol>
<p>In this installment, I&#8217;m going to cover a method added into <code>Enumerable</code> in Ruby 1.9: <code>Enumerable#cycle</code>. It&#8217;s particularly poorly-documented in RubyDoc.org, and there isn&#8217;t much written about it anywhere else.</p>
<h3>Enumerable#cycle Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerablecycle.jpg" alt="Graphic representation of the \&quot;cycle\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; class." title="Graphic representation of the \&quot;cycle\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; class." width="194" height="412" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Given a collection, creates an infinitely-repeating ordered source of its items.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>An optional block to act on the items in the infinitely repeating until the <code>break</code> statement is encountered.</td>
</tr>
<tr>
<th>Returns</th>
<td>An <code>Enumerable::Enumerator</code> that acts as the infinite source of the collection&#8217;s items.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001172">Enumerable#cycle</a></td>
</tr>
</table>
<h3>Enumerable#cycle and Arrays</h3>
<p>When used on an array and a block is provided, <code>cycle</code> passes each item to the block. Once the last array item has been passed to the block, <code>cycle</code> starts over again at the beginning of the array. <code>cycle</code> goes through the array forever unless it encounters a <code>break</code> statement in the block.</p>
<p><code>
<pre>
# This example is a slightly fancier version of the example
# you'll see at RubyDoc.org
days_of_week = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}
=> ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

# This will print the days of the week over and over,
# forever until you stop it with control-c.
days_of_week.cycle {|day| puts day}
=> Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
...

# The cycle can be broken with the "break" statement
days_of_week.cycle do |day|
    puts day
    break if day == "Friday"
end
=> Monday
Tuesday
Wednesday
Thursday
Friday
=> nil
</pre>
<p></code></p>
<p>The better use for <code>cycle</code> is when you use it to create an object that spits out the next item in a repeating sequence.</p>
<p><code>
<pre>
# Let's create an enumerator that we can use to give us
# days of the week in a repeating sequence.
days = days_of_week.cycle
=> #<enumerable::Enumerator:0x147c0b0>

# Enumerator's "next" method gives us the next day of the week
days.next
=> "Monday"

days.next
=> "Tuesday"

days.next
=> "Wednesday"

# Enumerator's "rewind" method resets the enumerator back
# to the first item
days.rewind
=> #<enumerable::Enumerator:0x14

days.next
=> "Monday"

...

# If you keep going, the enumerator will "wrap around" back
# to the beginning
days.next
=> "Saturday"

days.next
=> "Sunday"

days.next
=> "Monday"
</pre>
<p></code></p>
<p>How about one more example? We&#8217;ll use <code>Enumerable</code>&#8217;s <a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001167"><code>zip</code></a> method, an array of dinner items and the &#8220;days of the week&#8221; cycle object to create a meal plan:</p>
<p><code>
<pre>
# Here's an array of international cuisine
dinners = ["Jerk chicken", "Lamb vindaloo", "Chicken fried steak", \
"Yeung Chow fried rice", "Tonkatsu", "Coq au Vin", "Chunky bacon", \
"Pierogies", "Salisbury steak", "Bibim Bap", \
"Roast beef", "Souvlaki"]
=> ["Jerk chicken", "Lamb vindaloo", "Chicken fried steak",
"Yeung Chow fried rice", "Tonkatsu", "Coq au Vin", "Chunky bacon",
"Pierogies", "Salisbury steak", "Bibim Bap",
"Roast beef", "Souvlaki"]

# Let's draw up a mean plan!
days.zip(dinners) {|daily_meal| p daily_meal}
=> ["Monday", "Jerk chicken"]
["Tuesday", "Lamb vindaloo"]
["Wednesday", "Chicken fried steak"]
["Thursday", "Yeung Chow fried rice"]
["Friday", "Tonkatsu"]
["Saturday", "Coq au Vin"]
["Sunday", "Chunky bacon"]
["Monday", "Pierogies"]
["Tuesday", "Salisbury steak"]
["Wednesday", "Bibim Bap"]
["Thursday", "Roast beef"]
["Friday", "Souvlaki"]

# If we want to store our meal plan, we can do it this way
meal_plan = []
=> []

days.zip(dinners) {|daily_meal| meal_plan << daily_meal}
=> nil

meal_plan
=> [["Monday", "Jerk chicken"], ["Tuesday", "Lamb vindaloo"],
["Wednesday", "Chicken fried steak"], ["Thursday", "Yeung Chow fried rice"],
["Friday", "Tonkatsu"], ["Saturday", "Coq au Vin"],
["Sunday", "Chunky bacon"], ["Monday", "Pierogies"],
["Tuesday", "Salisbury steak"], ["Wednesday", "Bibim Bap"],
["Thursday", "Roast beef"], ["Friday", "Souvlaki"]]
</pre>
<p></code></p>
<h3>Enumerable#cycle and Hashes</h3>
<p>When used on a hash and a block is provided, collect and map pass each key/value pair in the hash to the block, which you can “catch” as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p>Each key/value pair is passed to the block, where the operation in the block is performed on the item. Once the last hash item has been passed to the block, <code>cycle</code> starts over again at the beginning of the hash. <code>cycle</code> goes through the hash forever unless it encounters a <code>break</code> statement in the block.</p>
<p><code>
<pre>
# Here we'll take the RubyDoc.org example for "cycle"
# but apply it to a hash of the crew of the Enterprise-D
crew = {:captain => "Picard", :first_officer => "Riker", \
:science_officer => "Data", :tactical_officer => "Worf"}
=> {:captain=>"Picard", :first_officer=>"Riker",
:science_officer=>"Data", :tactical_officer=>"Worf"}

# This will print the crew's rank and name over and over,
# forever until you stop it with control-c.
crew.cycle {|crewmember| p crewmember}
=> [:captain, "Picard"]
[:first_officer, "Riker"]
[:science_officer, "Data"]
[:tactical_officer, "Worf"]
[:captain, "Picard"]
[:first_officer, "Riker"]
[:science_officer, "Data"]
[:tactical_officer, "Worf"]
[:captain, "Picard"]
[:first_officer, "Riker"]
[:science_officer, "Data"]
[:tactical_officer, "Worf"]
[:captain, "Picard"]
[:first_officer, "Riker"]
...

# The cycle can be broken with the "break" statement
crew.cycle do |rank, name|
    puts "Rank: #{rank} - Name: #{name}"
    break if rank == :science_officer
end
=> Rank: captain - Name: Picard
Rank: first_officer - Name: Riker
Rank: science_officer - Name: Data
=> nil
</pre>
<p></code></p>
<p>We can use the same technique that we used with arrays and use <code>cycle</code> to create an object that spits out the next item in a cycling hash. Each time we get an item from the object, it comes in the form of a two-element array where the first element is the key and the second element is the corresponding value.</p>
<p><code>
<pre>
# Let's create an enumerator that we can use to give us
# the Enterprise-D crew's rank and name in a repeating sequence.
crewmembers = crew.cycle
=> #<enumerable::Enumerator:0x117fdf8>

# numerator’s “next” method gives us the next crewmember
crewmembers.next
=> [:captain, "Picard"]

crewmembers.next
=> [:first_officer, "Riker"]

crewmembers.next
=> [:science_officer, "Data"]

# Enumerator’s “rewind” method resets the enumerator back
# to the first item
crewmembers.rewind
=> #<enumerable::Enumerator:0x117fdf8>

crewmembers.next
=> [:captain, "Picard"]

...

# If you keep going, the enumerator will “wrap around” back
# to the beginning
crewmembers.next
=> [:tactical_officer, "Worf"]

crewmembers.next
=> [:captain, "Picard"]

crewmembers.next
=> [:first_officer, "Riker"]
</pre>
<p></code></p>
<p>Let&#8217;s try one more example! In this one, we&#8217;ll use <code>cycle</code> to create three different enumerators &#8212; two made from arrays, one from a hash &#8212; to assign cooking chores for the Enterprise-D crew for the next ten days.</p>
<p><code>
<pre>
# Create an enumerator for days
days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}.cycle
=> #<enumerable::Enumerator:0x14c678c>

# Create an enumerator for dinners
dinners = ["Jerk chicken", "Lamb vindaloo", "Chicken fried steak", \
"Yeung Chow fried rice", "Tonkatsu", "Coq au Vin", "Chunky bacon", \
"Pierogies", "Salisbury steak", "Bibim Bap", \
"Roast beef", "Souvlaki"].cycle
=> #<enumerable::Enumerator:0x1496f14>

# Make sure we're starting from the beginning of the crew hash
crewmembers.rewind
=> #<enumerable::Enumerator:0x1496f14>

# Let's assign dinner-cooking duties to the crew!
10.times do
    day = days.next
    dinner = dinners.next
    chef = crewmembers.next[1]
    puts "On #{day}, Crewman #{chef} will prepare #{dinner}."
end
=> On Monday, Crewman Picard will prepare Jerk chicken.
On Tuesday, Crewman Riker will prepare Lamb vindaloo.
On Wednesday, Crewman Data will prepare Chicken fried steak.
On Thursday, Crewman Worf will prepare Yeung Chow fried rice.
On Friday, Crewman Picard will prepare Tonkatsu.
On Saturday, Crewman Riker will prepare Coq au Vin.
On Sunday, Crewman Data will prepare Chunky bacon.
On Monday, Crewman Worf will prepare Pierogies.
On Tuesday, Crewman Picard will prepare Salisbury steak.
On Wednesday, Crewman Riker will prepare Bibim Bap.
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#count</title>
		<link>http://www.globalnerdy.com/2008/07/02/enumerating-enumerable-enumerablecount/</link>
		<comments>http://www.globalnerdy.com/2008/07/02/enumerating-enumerable-enumerablecount/#comments</comments>
		<pubDate>Wed, 02 Jul 2008 18:19:27 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[count]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby 1.9]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1771</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerablecount.jpg" alt="Graphic representation of the Enumberable#count method in Ruby" title="Graphic representation of the Enumerable#count method in Ruby" width="201" height="310" /></p>

<p>Welcome to the fourth installment of <cite>Enumerating Enumerable</cite>, a series of articles in which I challenge myself to do a better job of documenting Ruby's <code>Enumerable</code> module than <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org does</a>. In this article, I'll cover <code>Enumerable#count</code>, one of the new methods added to Enumerable in Ruby 1.9.</p>

<p>In case you missed the earlier installments, they're listed (and linked) below:
<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>
</ol>
</p>

<p><a href="http://globalnerdy.com/2008/07/02/enumerating-enumerable-enumerablecount/"><strong>Read on for more about Enumerable#count...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p>Welcome to the fourth installment of <cite>Enumerating Enumerable</cite>, a series of articles in which I challenge myself to do a better job of documenting Ruby&#8217;s <code>Enumerable</code> module than <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org does</a>. In this article, I&#8217;ll cover <code>Enumerable#count</code>, one of the new methods added to Enumerable in Ruby 1.9.</p>
<p>In case you missed the earlier installments, 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>
</ol>
<h3>Enumerable#count Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/ruby_enumerablecount.jpg" alt="Graphic representation of the Enumberable#count method in Ruby" title="Graphic representation of the Enumerable#count method in Ruby" width="201" height="310" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>How many items in the collection meet the given criteria?</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>Either:</p>
<ul>
<li>An argument to be matched against the items in the collection</li>
<li>A block containing an expression to test the items in the collection</li>
</ul>
</td>
</tr>
<tr>
<th>Returns</th>
<td>The number of items in the collection that meet the given criteria.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001138">Enumerable#count</a></td>
</tr>
</table>
<h3>Enumerable#count and Arrays</h3>
<p>When used on an array and an argument is provided, <code>count</code> returns the number of times the value of the argument appears in the array:</p>
<p><code>
<pre>
# How many instances of "zoom" are there in the array?
["zoom", "schwartz", "profigliano", "zoom"].count("zoom")
=> 2

# Prior to Ruby 1.9, you'd have to use this equivalent code:
["zoom", "schwartz", "profigliano", "zoom"].select {|word| word == "zoom"}.size
=> 2
</pre>
<p></code></p>
<p>When used on an array and a block is provided, <code>count</code> returns the number of items in the array for which the block returns <code>true</code>:</p>
<p><code>
<pre>
# How many members of "The Mosquitoes" (a Beatles-esque band that appeared on
# "Gilligan's Island") have names following the "B*ngo" format?
["Bingo", "Bango", "Bongo", "Irving"].count {|bandmate| bandmate =~ /B[a-z]ngo/}
=> 3

# Prior to Ruby 1.9, you'd have to use this equivalent code:
["Bingo", "Bango", "Bongo", "Irving"].select {|bandmate| bandmate =~ /B[a-z]ngo/}.size
</pre>
<p></code></p>
<p>RubyDoc.org says that when <code>count</code> is used on an array without an argument or a block, it simply returns the number of items in the array (which is what the <code>length</code>/<code>size</code> methods do). However, when I&#8217;ve tried it in <strong>irb</strong> and <strong>ruby</strong>, I got results like this:</p>
<p><code>
<pre>
[1, 2, 3, 4].count
=> #&lt;Enumerable::Enumerator:0x189d784&gt;
</pre>
<p></code></p>
<h3>Enumerable#count and Hashes</h3>
<p>As with arrays, when used on a hash and an argument is provided, <code>count</code> returns the number of times the value of the argument appears in the hash. The difference is that for the comparison, each key/value pair is treated as a two-element array, with the key being element 0 and the value being element 1.</p>
<p><code>
<pre>
# Here's a hash where the names of recent movies are keys
# and their metacritic.com ratings are the corresponding values.
movie_ratings = {"Get Smart" => 53, "Kung Fu Panda" => 88, "The Love Guru" => 15,
"Sex and the City" => 51, "Iron Man" => 93}
=> {"Get Smart"=>53, "Kung Fu Panda"=>88, "The Love Guru"=>15, "Sex and the City"=>51, "Iron Man"=>93}

# This statement will return a count of 0, since there is no item in movie_ratings
# that's just plain "Iron Man".
movie_ratings.count("Iron Man")
=> 0

# This statement will return a count of 1, since there is an item in movie_ratings
# with the key "Iron Man" and the corresponding value 93.
movie_ratings.count(["Iron Man", 93])
=> 1

# This statement will return a count of 0. There's an item in movie_ratings
# with the key "Iron Man", but its corresponding value is NOT 92.
movie_ratings.count(["Iron Man", 92])
=> 0
</pre>
<p></code></p>
<p><code>count</code> is not useful when used with a hash and an argument. It will only ever return two values:</p>
<ul>
<li><code>1</code> if the argument is a two-element array and there is an item in the hash whose key matches element [0] of the array and whose value matches element [1] of the array.</li>
<li><code>0</code> for all other cases.</li>
</ul>
<p>When used with a hash and a block, <code>count</code> is more useful. <code>count</code> passes each key/value pair in the hash to the block, which you can &#8220;catch&#8221; as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p>Each key/value pair is passed to the block and <code>count</code> returns the number of items in the hash for which the block returns <code>true</code>.</p>
<p><code>
<pre>
# Once again, a hash where the names of recent movies are keys
# and their metacritic.com ratings are the corresponding values.
movie_ratings = {"Get Smart" => 53, "Kung Fu Panda" => 88, "The Love Guru" => 15,
 "Sex and the City" => 51, "Iron Man" => 93}
=> {"Get Smart"=>53, "Kung Fu Panda"=>88, "The Love Guru"=>15, "Sex and the City"=>51, "Iron Man"=>93}

# How many movie titles in the collection start
# in the first half of the alphabet?
# (Using a one-parameter block)
movie_ratings.count {|movie| movie[0] <= "M"}
=> 3

# How many movie titles in the collection start
# in the first half of the alphabet?
# (This time using a two-parameter block)
movie_ratings.count {|title, rating| title <= "M"}
=> 3

# Here's how you'd do it in pre-1.9 Ruby:
movie_ratings.select {|movie| movie[0] <= "M"}.size
=> 3
# or...
movie_ratings.select {|title, rating| title <= "M"}.size
=> 3

# How many movies in the collection had a rating
# higher than 80?
# (Using a one-parameter block)
movie_ratings.count {|movie| movie[1] > 80}
=> 2

# How many movies in the collection had a rating
# higher than 80?
# (This time using a two-parameter block)
movie_ratings.count {|title, rating| rating > 80}
=> 2

# Here's how you'd do it in pre-1.9 Ruby:
movie_ratings.select {|title, rating| rating > 80}.size
=> 2

# How many movies in the collection have both:
# - A title starting in the second half of the alphabet?
# - A rating less than 50?
# (Using a one-parameter block)
movie_ratings.count {|movie| movie[0] >= "M" &#038;&#038; movie[1] < 50}
=> 1

# How many movies in the collection have both:
# - A title starting in the second half of the alphabet?
# - A rating less than 50?
# (This time using a two-parameter block)
movie_ratings.count {|title, rating| title >= "M" &#038;&#038; rating < 50}
=> 1

# Here's how you'd do it in pre-1.9 Ruby:
movie_ratings.select {|title, rating| title >= "M" &#038;&#038; rating < 50}.size
=> 1
</pre>
<p></code></p>
<p>(You should probably skip <cite>The Love Guru</cite> completely, or at least until it gets aired on TV for free.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/02/enumerating-enumerable-enumerablecount/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#collect/Enumerable#map</title>
		<link>http://www.globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/</link>
		<comments>http://www.globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 04:00:42 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[collect]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1768</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p style="text-align:center;"><a href="http://globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/ruby_enumerablecollect_enumerablemap.jpg" alt="Graphic representation of Ruby\&#039;s \&#34;Enumerable#collect / Enumerable#map\&#34; methods" title="ruby_enumerablecollect_enumerablemap" width="400" height="319" /></a></p>

<p>Here we are the third installment of <cite>Enumerating Enumerable</cite>, my attempt to do a better job of documenting Ruby's <code>Enumerable</code> module than <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org does</a>. In this installment, I cover <code>Enumerable#collect</code> and its syntactic sugar twin (and the one I prefer), <code>Enumerable#map</code>.</p>

<p><a href="http://globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/"><strong>Click here to read about <code>Enumerable#collect</code>/<code>Enumerable#map</code>...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p>Here we are the third installment of <cite>Enumerating Enumerable</cite>, my attempt to do a better job of documenting Ruby&#8217;s <code>Enumerable</code> module than <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">RubyDoc.org does</a>. In this installment, I cover <code>Enumerable#collect</code> and its syntactic sugar twin (and the one I prefer), <code>Enumerable#map</code>.</p>
<p>In case you missed the earlier installments, 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>
</ol>
<h3>Enumerable#collect/Enumerable#map Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/ruby_enumerablecollect_enumerablemap.jpg" alt="Graphic representation of Ruby\&#039;s \&quot;Enumerable#collect / Enumerable#map\&quot; methods" title="ruby_enumerablecollect_enumerablemap" width="400" height="319" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Create a new array by performing some operation on every item in the given collection. <code>collect</code> and <code>map</code> are synonyms &#8212; you can use either. I personally prefer <code>map</code> as it&#8217;s shorter and makes sense if you think of the method as being like <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)">functional mapping</a>.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.8 and 1.9</td>
</tr>
<tr>
<th>Expects</th>
<td>A block containing the criteria. This block is optional, but you&#8217;re likely to use one in most cases.</td>
</tr>
<tr>
<th>Returns</th>
<td>An array made up of items created by performing some operation on the given collection.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001145">Enumerable#collect</a> / <a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001146">Enumerable#map</a></td>
</tr>
</table>
<h3>Enumerable#collect/Enumerable#map and Arrays</h3>
<p>When used on an array and a block is provided, <code>collect</code>/<code>map</code> passes each item to the block, where the operation in the block is performed on the item and the result is then added to the result array. Note the the result array has the same number of elements as the given array.</p>
<p><code>
<pre>
[1, 2, 3, 4].map {|number| number ** 2}
=> [1, 4, 9, 16]

["Aqua", "Bat", "Super", "Wonder Wo"].map {|adjective| adjective + "man"}
=> ["Aquaman", "Batman", "Superman", "Wonder Woman"]
</pre>
<p></code></p>
<p>When the block is omitted, <code>collect</code>/<code>map</code> uses this implied block: <code>{|item| item}</code>, which means when applied on an array without a block, <code>collect</code>/<code>map</code> is the <em>identity function</em> &#8212; the resulting array is the same as the given array.</p>
<p><code>
<pre>
[1, 2, 3, 4].map
=> [1, 2, 3, 4]

["Aqua", "Bat", "Super", "Wonder Wo"].map
=> ["Aqua", "Bat", "Super", "Wonder Wo"]
</pre>
<p></code></p>
<h3>Enumerable#collect/Enumerable#map and Hashes</h3>
<p>When used on a hash and a block is provided, <code>collect</code> and <code>map</code> pass each key/value pair in the hash to the block, which you can &#8220;catch&#8221; as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p>Each key/value pair is passed to the block, where the operation in the block is performed on the item and the result is then added to the result array. Note the the result array has the same number of elements as the given array.</p>
<p><code>
<pre>
burgers = {"Big Mac" => 300, "Whopper with cheese" => 450, "Wendy's Double with cheese" => 320}

# What if I had just half a burger?
burgers.map {|burger| burger[1] / 2}
=> [160, 150, 225]

burgers.map {|sandwich, calories| calories / 2}
=> [160, 150, 225]

burgers.map {|burger| "Have a tasty #{burger[0]}!"}
=> ["Have a tasty Wendy's Double with cheese!", "Have a tasty Big Mac!",
 "Have a tasty Whopper with cheese!"]

burgers.map {|sandwich, calories| "Have a tasty #{sandwich}!"}
=> ["Have a tasty Wendy's Double with cheese!", "Have a tasty Big Mac!",
 "Have a tasty Whopper with cheese!"]

burgers.map {|sandwich, calories| ["Half a #{sandwich}", calories / 2]}
=> [["Half a Wendy's Double with cheese", 160], ["Half a Big Mac", 150],
 ["Half a Whopper with cheese", 225]]
</pre>
<p></code></p>
<p>When the block is omitted, <code>collect</code>/<code>map</code> uses this implied block: <code>{|item| item}</code>, which means when applied on an hash without a block, <code>collect</code>/<code>map</code> returns an array containing a set of two-item arrays, one for each key/value pair in the hash. For each two-item array, item 0 is the key and item 1 is the corresponding value.</p>
<p><code>
<pre>
burgers = {"Big Mac" => 300, "Whopper with cheese" => 450, "Wendy's Double with cheese" => 320}

burgers.map
=> [["Wendy's Double with cheese", 320], ["Big Mac", 300], ["Whopper with cheese", 450]]
</pre>
<p></code></p>
<h3>Special Case: Using Enumerable#collect/Enumerable#map on Empty Arrays and Hashes</h3>
<p>When applied to an empty array or hash, with or without a block, <code>collect</code> and <code>map</code> always return an empty array.</p>
<p><code>
<pre>
# Let's try it with an empty array
[].map
=> []

[].map {|item| item * 2}
=> []

# Now let's try it with an empty hash
{}.map
=> []

{}.map {|sandwich, calories| "Have a tasty #{sandwich}!"}
=> []
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#any?</title>
		<link>http://www.globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/</link>
		<comments>http://www.globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 04:00:39 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[any?]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1767</guid>
		<description><![CDATA[<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>

<p style="text-align:center;"><a href="http://globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/ruby_enumerableany.jpg" alt="Graphic representing Ruby\&#039;s Enumerable#any? method" title="ruby_enumerableany" width="201" height="310" /></a></p>

<p>Welcome to the second installment of <cite>Enumerating Enumerable</cite>, my project to do a better job of documenting Ruby's <code>Enumerable</code> module than <a href="http://rubydoc.org/">RubyDoc.org</a>. This installment will cover <code>Enumerable#any?</code>, which I like to think of as <code>Enumerable.all?</code>'s more easy-going cousin (I covered <code>Enumerable.all?</code> in <a href="http://globalnerdy.com/2008/06/23/enumerating-enumerable-enumerableall/">the previous installment</a>).</p>

<p><a href="http://globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/"><strong>Click here to read about <code>Enumerable#any?</code>...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/enumerating_enumerable.jpg" alt="" title="enumerating_enumerable" width="350" height="120" /></p>
<p>Welcome to the second installment of <cite>Enumerating Enumerable</cite>, my project to do a better job of documenting Ruby&#8217;s <code>Enumerable</code> module than <a href="http://rubydoc.org/">RubyDoc.org</a>. This installment will cover <code>Enumerable#any?</code>, which I like to think of as <code>Enumerable.all?</code>&#8217;s more easy-going cousin (I covered <code>Enumerable.all?</code> in <a href="http://globalnerdy.com/2008/06/23/enumerating-enumerable-enumerableall/">the previous installment</a>).</p>
<h3>Enumerable#any? Quick Summary</h3>
<p style="text-align:center;"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/06/ruby_enumerableany.jpg" alt="Graphic representing Ruby\&#039;s Enumerable#any? method" title="ruby_enumerableany" width="201" height="310" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Do any of the items in the collection meet the given criteria?</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.8 and 1.9</td>
</tr>
<tr>
<th>Expects</th>
<td>A block containing the criteria. This block is optional, but you&#8217;re likely to use one in most cases.</td>
</tr>
<tr>
<th>Returns</th>
<td><code>true</code> if any of the items in the collection meet the given criteria.</p>
<p>        <code>false</code> if none of the items in the collection does not meet the given criteria.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001153">Enumerable#any?</a></td>
</tr>
</table>
<h3>Enumerable#any? and Arrays</h3>
<p>When used on an array and a block is provided, <code>any?</code> passes each item to the block. If the block returns <code>true</code> for any item during this process, <code>any?</code> returns <code>true</code>; otherwise, it returns <code>false</code>.</p>
<p><code>
<pre>
# "Fromage de Montagne de Savoie" is the longest-named cheese in this list
# at a whopping 29 characters
cheeses = ["feta", "cheddar", "stilton", "camembert", "mozzarella", "Fromage de Montagne de Savoie"]

cheeses.any? {|cheese| cheese.length >= 25}
=> true

cheeses.any? {|cheese| cheese.length >= 35}
=> false
</pre>
<p></code></p>
<p>When the block is omitted, <code>any?</code> uses this implied block: <code>{|item| item}</code>. Since everything in Ruby evaluates to <code>true</code> except for <code>false</code> and <code>nil</code>, using <code>any?</code> without a block is effectively a test to see if any of the items in the collection evaluate to <code>true</code> (or conversely, if all the values in the array evaluate to  <code>false</code> or <code>nil</code>).</p>
<p><code>
<pre>
cheeses.any?
=> true

cheeses = [false, nil]
=> [false, nil]

cheeses.any?
=> false

# Remember that in Ruby, everything except for false and nil evaluates to true:
cheeses << 0
=> [false, nil, 0]

>> cheeses.any?
=> true
</pre>
<p></code></p>
<h3>Enumerable#any? and Hashes</h3>
<p>When used on a hash and a block is provided, <code>any?</code> passes each key/value pair in the hash to the block, which you can &#8220;catch&#8221; as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p>If the block returns <code>true</code> for any item during this process, <code>any?</code> returns <code>true</code>; otherwise, it returns <code>false</code>.</p>
<p><code>
<pre>
# Here's a hash where for each key/value pair, the key is a programming language and
# the corresponding value is the year when that language was first released
# The keys range in value from "Javascript" to "Ruby", and the values range from
# 1987 to 1996
languages = {"Javascript" => 1996, "PHP" => 1994, "Perl" => 1987, "Python" => 1991, "Ruby" => 1993}

languages.any? {|language| language[0] < "Pascal"}
=> true

languages.any? {|language, year_created| language < "Pascal"}
=> true

languages.any? {|language| language[0] < "Fortran"}
=> false

languages.any? {|language, year_created| language < "Fortran"}
=> false

languages.any? {|language| language[0] >= "Basic" and language[1] <= 1995}
=> true

languages.any? {|language, year_created| language >= "Basic" and year_created <= 1995}
=> true

languages.any? {|language| language[0] >= "Basic" and language[1] <= 1985}
=> false

languages.any? {|language, year_created| language >= "Basic" and year_created <= 1985}
=> false
</pre>
<p></code></p>
<p>Using <code>any?</code> without a block on a hash is meaningless, as it will always return <code>true</code>. When the block is omitted, <code>any?</code> uses this implied block: <code>{|item| item}</code>. In the case of a hash, <code>item</code> will always be a two-element array, which means that it will never evaluate as <code>false</code> nor <code>nil</code>.</p>
<p>And yes, even this hash, when run through <code>any?</code>, will still return <code>true</code>:</p>
<p><code>
<pre>
{false => false, nil => nil}.any?
=> true
</pre>
<p></code></p>
<h3>Special Case: Using Enumerable#any? on Empty Arrays and Hashes</h3>
<p>When applied to an empty array or hash, with or without a block, <code>any?</code> always returns <code>false</code>. That’s because with an empty collection, there are no values to process and return a <code>true</code> value.</p>
<p>Let’s look at the case of empty arrays:</p>
<p><code>
<pre>
cheeses = []
=> []

cheeses.any? {|cheese| cheese.length >= 25}
=> false

cheeses.any?
=> false

# Let's try applying "any?" to a non-empty array
# using a block that ALWAYS returns true:
["Gruyere"].any? {|cheese| true}
=> true

# ...but watch what happens when we try the same thing
# with an EMPTY array!
[].any? {|cheese| true}
=> false
</pre>
<p></code></p>
<p>…now let’s look at the case of empty hashes:</p>
<p><code>
<pre>
languages = {}
=> {}

languages.any? {|language| language[0] < "Pascal"}
=> false

languages.any? {|language, year_created| language < "Pascal"}
=> false

languages.any?
=> false

# Let's try applying "any?" to a non-empty hash
# using a block that ALWAYS returns true:
{"Lisp" => 1959}.any? {|language| true}
=> true

# ...but watch what happens when we try the same thing
# with an EMPTY hash!
{}.any? {|language| true}
=> false
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>How Map/Reduce/Filter Can Rock Your World</title>
		<link>http://www.globalnerdy.com/2008/06/16/how-mapreducefilter-can-rock-your-world/</link>
		<comments>http://www.globalnerdy.com/2008/06/16/how-mapreducefilter-can-rock-your-world/#comments</comments>
		<pubDate>Mon, 16 Jun 2008 20:48:27 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[dynamic languages]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[fold]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[reduce]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1734</guid>
		<description><![CDATA[Better late than never: C# 3.0 will feature map, reduce and filter, and Dare &#8220;Carnage4Life&#8221; Obasanjo explains how to rock these features. He concludes the article with &#8220;If your programming language doesn&#8217;t support lambda functions or have map/reduce/filter functions built in, you just might be a Blub Programmer who is missing out on being more [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Better late than never: <a href="http://www.25hoursaday.com/weblog/2008/06/16/FunctionalProgrammingInC30HowMapReduceFilterCanRockYourWorld.aspx"><strong>C# 3.0 will feature <code>map</code>, <code>reduce</code> and <code>filter</code>, and Dare &#8220;Carnage4Life&#8221; Obasanjo explains how to rock these features.</strong></a> He concludes the article with &#8220;If your programming language doesn&#8217;t support lambda functions or have map/reduce/filter functions built in, you just might be a <a href="http://weblog.raganwald.com/2006/10/are-we-blub-programmers.html">Blub Programmer</a> who is missing out on being more productive because your programming language doesn&#8217;t support &#8216;esoteric&#8217; or &#8216;weird&#8217; features,&#8221; which sounds kind of weird in an article about C#, a language that could only be Blubbier if its name were BlubLang or Blub#. I suspect I&#8217;ve woken up in some upside-down parallel universe again!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/06/16/how-mapreducefilter-can-rock-your-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Ruby’s &#8220;Enumerable&#8221; Module, Part 3: &#8220;detect&#8221;, a.k.a. &#8220;find&#8221;</title>
		<link>http://www.globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-3-detect-aka-find/</link>
		<comments>http://www.globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-3-detect-aka-find/#comments</comments>
		<pubDate>Thu, 07 Feb 2008 04:59:32 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[detect]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[find]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-3-detect-aka-find/</guid>
		<description><![CDATA[<p style="text-align:center;"><a href="http://globalnerdy.com/2008/02/06/enumerating-ruby’s-enumerable-module-part-3-detect-aka-find/"><img src='http://globalnerdy.com/wordpress/wp-content/uploads/2008/02/enumerable_find.jpg' alt='Enumerable#find: A magnifying glass focused on a ruby' width="400" height="300" /></a></p>

Here's the third installment in my series on the method in Ruby's <code>Enumerable</code> module. This one focuses on the <strong>find</strong> method. <a href="http://globalnerdy.com/2008/02/06/enumerating-ruby’s-enumerable-module-part-3-detect-aka-find/"><strong>Read on...</strong></a>]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align:center;"><img src='http://globalnerdy.com/wordpress/wp-content/uploads/2008/02/enumerable_find.jpg' alt='Enumerable#find: A magnifying glass focused on a ruby' width="400" height="300" /></p>
<p>Welcome to the third installment in my series of articles on the methods of Ruby&#8217;s <code>Enumerable</code> module. This series is meant to address some of the shortcomings in the official documentation</p>
<p>In case you missed the first two, here they are:</p>
<ol>
<li><a href="http://globalnerdy.com/2008/01/29/enumerating-rubys-enumerable-module-part-1-all-and-any/"><code>all?</code> and <code>any?</code></a></li>
<li><a href="http://globalnerdy.com/2008/02/06/enumerating-ruby’s-enumerable-module-part-2-collect-aka-map/"><code>collect</code>/<code>map</code></a></li>
</ol>
<p>In this installment, I&#8217;m going to cover the <code>find</code> method. This is a particularly interesting one because it covers <code>detect</code>/<code>find</code>&#8217;s little-talked about optional parameter.</p>
<h3>detect, a.k.a. find</h3>
<li><strong>In plain language:</strong> What&#8217;s the first item in the collection that meets the given criteria?</li>
<li><strong>Ruby.Doc.org&#8217;s entry:</strong> <a href="http://ruby-doc.org/core/classes/Enumerable.html#M003154"><code>Enumerable#detect</code> / <code>Enumerable#find</code></a></li>
<li><strong>Expects:</strong>
<ul>
<li>A block containing the criteria.</li>
<li>An optional argument containing a proc that calculates a &#8220;default&#8221; value &#8212; that is, the value to return if no item in the collection matches the criteria.</li>
</ul>
</li>
<li><strong>Returns:</strong>
<ul>
<li>The first item in the collection that matches the criteria, if one exists.</li>
<li>If no such item exists in the collection:
<ul>
<li><code>nil</code> if no argument is provided</li>
<li>The value of the argument if one is provided</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><code>detect</code> and <code>find</code> are synonyms &#8212; you can use either. I personally prefer find, as it&#8217;s shorter and a good match with a related method, <code>find_all</code>. I also just think that &#8220;find&#8221; conveys the method&#8217;s functionality much better than &#8220;detect&#8221;.</p>
<h4>Using <code>detect</code>/<code>find</code> with Arrays</h4>
<p>When used on an array without an argument, <code>detect</code>/<code>find</code> passes each item from the collection to the block and&#8230;</p>
<ul>
<li>If the current item causes the block to return a value that doesn&#8217;t evaluate to <code>false</code>, <code>detect</code>/<code>find</code> stops going through collection and returns the item.</li>
<li>If no item in the collection causes the block to return a value that doesn&#8217;t evaluate to <code>false</code>, <code>detect</code>/<code>find</code> returns <code>nil</code>.</li>
</ul>
<p><code>
<pre>
classic_rock_bands = ["AC/DC", "Black Sabbath", "Queen", "Scorpions"]

classic_rock_bands.find {|band| band > "Led Zeppelin"}
=> "Queen"

classic_rock_bands.find {|band| band > "ZZ Top"}
=> nil
</pre>
<p></code></p>
<p>Using the optional argument is a topic big enough to merit its own section, which appears later in this article.</p>
<h4>Using <code>detect</code>/<code>find</code> with Hashes</h4>
<p>With hashes, <code>detect</code>/<code>find</code> passes each key/value pair in the hash to the block, which you can “catch” as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p><code>detect</code>/<code>find</code> is one of those methods of <code>Enumerable</code> that works a little oddly since:</p>
<ul>
<li>The result it returns depends on the order of the collection</li>
<li>We&#8217;re always told that hashes don&#8217;t really any order (there seems to be one, but it&#8217;s shrouded in mystery).</li>
</ul>
<p><code>
<pre>
metacritic_ratings = {"Juno" => 81, "American Gangster" => 76, \
                      "Golden Compass" => 51, "Meet the Spartans" => 9}
=> {"American Gangster"=>76, "Golden Compass"=>51, "Juno"=>81, "Meet the Spartans"=>9}

metacritic_ratings.find {|metacritic_rating| metacritic_rating[1] > 80}
=> ["Juno", 81]

metacritic_ratings.find {|film, rating| rating > 80}
=> ["Juno", 81]

metacritic_ratings.find {|film, rating| rating > 90}
=> nil
</pre>
<p></code></p>
<h4>Using <code>detect</code>/<code>find</code> with the Optional Argument</h4>
<p><code>detect</code>/<code>find</code>&#8217;s optional argument lets you specify a proc or lambda whose return value will be the result in cases where no object in the collection matches the criteria.</p>
<p>(Unfortunately, a complete discussion of procs and lambdas is beyond the scope of this article. I highly recommend looking at Eli Bendersky&#8217;s very informative article, <a href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/"><cite>Understanding Ruby blocks, Procs and methods</cite></a>.)</p>
<p>I think that the optional argument is best explained through examples&#8230;</p>
<p><code>
<pre>
classic_rock_bands = ["AC/DC", "Black Sabbath", "Queen", "Scorpions"]

# Let's define a proc that will simply return the default band's name
# for cases where none of the bands in the array meets the criteria.
default_band = Proc.new {"ABBA"}

# Procs are objects, so using a proc's name alone isn't sufficient
to invoke its code -- doing so will simply return the proc object.
default_band
=> #&lt;Proc:0x00553f34@(irb):31&gt;
# (The actual value will be different for you, but you get the idea.)

# To call a proc, you have to use its "call" method:
default_band.call
=> "ABBA"

# detect/find calls the "call" method of the object you provide as the argument
# if no item in the collection matches the criteria in the block.
classic_rock_bands.find(default_band) {|band| band > "Led Zeppelin"}
=> "Queen"

classic_rock_bands.find(default_band) {|band| band > "ZZ Top"}
=> "ABBA"

# Let's try something a little fancier, and use a lambda this time.
# The differences between procs and lambdas are very fine -- I suggest
# you check Eli Bendersky's article for those differences.
random_band = lambda do
	fallback_bands = ["Britney Spears", "Christina Aguilera", "Ashlee Simpson"]
	fallback_bands[rand(fallback_bands.size)]
end

# Let's give it a try...
classic_rock_bands.find(random_band) {|band| band > "ZZ Top"}
=> "Britney Spears"
>> classic_rock_bands.find(random_band) {|band| band > "ZZ Top"}
=> "Ashlee Simpson"
>> classic_rock_bands.find(random_band) {|band| band > "ZZ Top"}
=> "Christina Aguilera"
</pre>
<p></code></p>
<p>To see a &#8220;real&#8221; application of <code>detect</code>/<code>find's</code> optional argument, see <a href="http://www.rubyquiz.com/quiz77.html">this <cite>Ruby Quiz</cite> problem.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-3-detect-aka-find/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Enumerating Ruby’s &#8220;Enumerable&#8221; Module, Part 2: &#8220;collect&#8221;, a.k.a. &#8220;map&#8221;</title>
		<link>http://www.globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-2-collect-aka-map/</link>
		<comments>http://www.globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-2-collect-aka-map/#comments</comments>
		<pubDate>Wed, 06 Feb 2008 05:32:09 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-2-collect-aka-map/</guid>
		<description><![CDATA[<p><a href="http://globalnerdy.com/2008/02/06/enumerating-ruby’s-enumerable-module-part-2-collect-aka-map/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/01/ruby.thumbnail.jpg" width="110" height="120" alt="Ruby gemstone" align="left" /></a>Here's part 2 of my ongoing series covering the methods in Ruby's <code>Enumerable</code> module -- this one covers the <code>collect</code> method, a.k.a. <code>map</code>.</p>

<p><a href="http://globalnerdy.com/2008/02/06/enumerating-ruby’s-enumerable-module-part-2-collect-aka-map/"><strong>Read on...</strong></a></p>]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://globalnerdy.com/2008/01/29/enumerating-rubys-enumerable-module-part-1-all-and-any/">In the last article in this series covering the methods in Ruby&#8217;s <code>Enumerable</code> module</a>, I covered <code>all?</code> and <code>any?</code>. In this installment, I&#8217;ll look at the <code>collect</code> method, a.k.a. the <code>map</code> method.</p>
<h3>collect, a.k.a. map</h3>
<ul>
<li><strong>In plain language:</strong> Create an array by performing some operation on every item in the given collection.</li>
<li><strong>Ruby.Doc.org&#8217;s entry:</strong> <a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M003158"><code>Enumerable#collect</code> / <code>Enumerable#map</code></a></li>
<li><strong>Expects:</strong> A block containing the operation (it&#8217;s optional, but you&#8217;re likely to use one most of the time).</li>
<li><strong>Returns:</strong> An array made up of items created by performing some operation on the given collection.</li>
</ul>
<p><code>collect</code> and <code>map</code> are synonyms &#8212; you can use either. I personally prefer <code>map</code> as it&#8217;s shorter and makes more sense: I view the operation as using a function to map a collection to an array.</p>
<h4>Using <code>collect</code>/<code>map</code> with Arrays</h4>
<p>When used on an array and a block is provided, <code>collect</code>/<code>map</code> passes each item to the block, where the operation in the block is performed on the item and the result is then added to the result array. Note the the result array has the same number of elements as the given array.</p>
<p><code>
<pre>
[1, 2, 3, 4].map {|number| number ** 2}
=> [1, 4, 9, 16]

["Aqua", "Bat", "Super", "Wonder Wo"].map {|adjective| adjective + "man"}
=> ["Aquaman", "Batman", "Superman", "Wonder Woman"]
</pre>
<p></code></p>
<p>When the block is omitted, <code>collect</code>/<code>map</code> uses this implied block: <code>{|item| item}</code>, which means when applied on an array without a block, <code>collect</code>/<code>map</code> is the identity function &#8212; the resulting array is the same as the given array.</p>
<p><code>
<pre>
[1, 2, 3, 4].map
=> [1, 2, 3, 4]

["Aqua", "Bat", "Super", "Wonder Wo"].map
=> ["Aqua", "Bat", "Super", "Wonder Wo"]
</pre>
<p></code></p>
<h4>Using <code>collect</code>/<code>map</code> with Hashes</h4>
<p>When used on a hash and a block is provided, <code>collect</code>/<code>map</code> passes each key/value pair in the hash to the block, which you can &#8220;catch&#8221; as either:</p>
<ol>
<li>A two-element array, with the key as element 0 and its corresponding value as element 1, or</li>
<li>Two separate items, with the key as the first item and its corresponding value as the second item.</li>
</ol>
<p>Each key/value pair is passed to the block, where the operation in the block is performed on the item and the result is then added to the result array. Note the the result array has the same number of elements as the given array.</p>
<p><code>
<pre>
burgers = {"Big Mac" => 300, "Whopper with cheese" => 450, "Wendy's Double with cheese" => 320}

# What if I had just half a burger?
burgers.map {|burger| burger[1] / 2}
=> [160, 150, 225]

burgers.map {|sandwich, calories| calories / 2}
=> [160, 150, 225]

burgers.map {|burger| "Have a tasty #{burger[0]}!"}
=> ["Have a tasty Wendy's Double with cheese!", "Have a tasty Big Mac!", "Have a tasty Whopper with cheese!"]

burgers.map {|sandwich, calories| "Have a tasty #{sandwich}!"}
=> ["Have a tasty Wendy's Double with cheese!", "Have a tasty Big Mac!", "Have a tasty Whopper with cheese!"]

burgers.map {|sandwich, calories| ["Half a #{sandwich}", calories / 2]}
=> [["Half a Wendy's Double with cheese", 160], ["Half a Big Mac", 150], ["Half a Whopper with cheese", 225]]
</pre>
<p></code></p>
<p>When the block is omitted, <code>collect</code>/<code>map</code> uses this implied block: <code>{|item| item}</code>, which means when applied on an hash without a block, <code>collect</code>/<code>map</code> returns an array containing a set of two-item arrays, one for each key/value pair in the hash. For each two-item array, item 0 is the key and item 1 is the corresponding value.</p>
<p><code>
<pre>
burgers = {"Big Mac" => 300, "Whopper with cheese" => 450, "Wendy's Double with cheese" => 320}

burgers.map
=> [["Wendy's Double with cheese", 320], ["Big Mac", 300], ["Whopper with cheese", 450]]
</pre>
<p></code></p>
<h4>Special Case: Using <code>collect</code>/<code>map</code> on Empty Arrays and Hashes</h4>
<p>When applied to an empty array or hash, with or without a block, <code>all?</code> always returns <code>true</code>.</p>
<p><code>
<pre>
[].map
=> []

[].map {|item| item * 2}
=> []

{}.map
=> []

{}.map {|sandwich, calories| "Have a tasty #{sandwich}!"}
=> []
</pre>
<p></code></p>
<h3>In the Next Installment&#8230;</h3>
<p>&#8230;the <code>detect</code> (a.k.a. <code>find</code>) method.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/02/06/enumerating-ruby%e2%80%99s-enumerable-module-part-2-collect-aka-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Intro to Ruby’s “Enumerable” Module</title>
		<link>http://www.globalnerdy.com/2008/01/10/an-intro-to-ruby%e2%80%99s-%e2%80%9cenumerable%e2%80%9d-module/</link>
		<comments>http://www.globalnerdy.com/2008/01/10/an-intro-to-ruby%e2%80%99s-%e2%80%9cenumerable%e2%80%9d-module/#comments</comments>
		<pubDate>Thu, 10 Jan 2008 19:59:57 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/2008/01/10/an-intro-to-ruby%e2%80%99s-%e2%80%9cenumerable%e2%80%9d-module/</guid>
		<description><![CDATA[&#8220;If you&#8217;re still writing for loops, stop; there&#8217;s a better way.&#8221; In Ruby, for loops should be the exception. Make sure you know all about the functionality offered by the Enumerable module, which has methods for iterating through, sorting and searching arrays, hashes and other collection-type objects.
]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://jamesgolick.com/2008/1/6/an-introduction-to-ruby-s-enumerable-module"><strong>&#8220;If you&#8217;re still writing for loops, stop; there&#8217;s a better way.&#8221;</strong></a> In Ruby, <code>for</code> loops should be the exception. Make sure you know all about the functionality offered by the <code>Enumerable</code> module, which has methods for iterating through, sorting and searching arrays, hashes and other collection-type objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/01/10/an-intro-to-ruby%e2%80%99s-%e2%80%9cenumerable%e2%80%9d-module/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
