<?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; Enumerating Enumerable</title>
	<atom:link href="http://www.globalnerdy.com/tag/enumerating-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: A Cute Trick for Explaining inject / reduce / fold</title>
		<link>http://www.globalnerdy.com/2008/09/03/enumerating-enumerable-a-cute-trick-for-explaining-inject-reduce-fold/</link>
		<comments>http://www.globalnerdy.com/2008/09/03/enumerating-enumerable-a-cute-trick-for-explaining-inject-reduce-fold/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 15:52:03 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1446</guid>
		<description><![CDATA[
The next method I&#8217;m going to cover in Enumerating Enumerable &#8212; the series of articles in which I try to do a better job of documenting Ruby&#8217;s Enumerable module than Ruby-Doc.org does &#8212; is inject, a.k.a. reduce. Not only is it one of the trickiest methods to explain, it&#8217;s also one of the cornerstones of [...]]]></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>The next method I&#8217;m going to cover in <cite>Enumerating Enumerable</cite> &#8212; the series of articles in which I try to do a better job of documenting Ruby&#8217;s <code>Enumerable</code> module than Ruby-Doc.org does &#8212; is <code>inject</code>, a.k.a. <code>reduce</code>. Not only is it one of the trickiest methods to explain, it&#8217;s also one of the cornerstones of functional programming. I thought that I&#8217;d take a little time to explain what the function does.</p>
<h3>inject</h3>
<p>The term <code>inject</code> comes from Smalltalk and isn&#8217;t terribly descriptive. I remember reading the documentation for it and being all confused until I saw some examples. I then realized that I&#8217;d seen this function before, but under two different names.</p>
<h3>reduce</h3>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/best_accordion_picture_ever_old.jpg" alt="The Second-Best Accordion Picture Ever" title="The Second-Best Accordion Picture Ever" width="312" height="465" class="size-full wp-image-1462" /><br /><span class="caption">Burning Man 1999: gratuitous nudity and even more gratuitous accordion!</span></p>
<p>The <em>second</em> name by which I encountered this function is <code>reduce</code>, and it was at <a href="http://www.burningman.com/whatisburningman/1999/">Burning Man 1999</a>. I was to start a new job the week after Burning Man, and I had to learn at least some basic Python by then. So along with my camping gear, accordion and a kilo of candy for barter, I also brought my laptop (a 233Mhz Toshiba Sattelite with a whopping 96MB of RAM) and O&#8217;Reilly&#8217;s <a href="http://oreilly.com/catalog/9781565924642/"><cite>Learning Python</cite></a> and noodled during the downtime (early morning and afternoon) on Python 1.6. When I got to covering the <code>reduce</code> function, I was confused until I saw some examples, after which I realized that I&#8217;d seen that function before, but under a different name.</p>
<p>(You may have also heard of <code>reduce</code> through Google&#8217;s much-vaunted <a href="http://labs.google.com/papers/mapreduce.html">MapReduce</a> programming model.)</p>
<h3>fold</h3>
<p>The <em>first</em> name by which I encountered this function is <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)"><code>fold</code></a>, or more specifically, &#8220;fold left&#8221; or &#8220;foldl&#8221;, and it was at the <a href="http://research.cs.queensu.ca/home/cisc260/2007w/Resources.html">&#8220;Programming Paradigms&#8221;</a> course I took at <a href="http://queensu.ca/">Crazy Go Nuts University</a>. &#8220;Programming Paradigms&#8221; was a second-year course and had the reputation of being the most difficult course in the computer science curriculum. The <em>intended</em> purpose of this course was to provide students with an introduction to functional programming (these days, they use Haskell and Prolog, back then, it was <a href="http://en.wikipedia.org/wiki/Miranda_programming_language">Miranda</a>). Its actual effect was to make most of the students swear off functional programming for the rest of their lives.</p>
<p>In spite of the trauma from this course, I ended up remembering a lot from it that I was able to apply, first to Python and now to Ruby. One of these things is a cute little trick for cememnting in your mind what <code>fold</code> does.</p>
<h3>What Ruby-doc.org Says</h3>
<p>Before I cover that cute little trick, let&#8217;s take a look at what Ruby-doc.org&#8217;s documentation has to say about <code>Enumerable</code>&#8217;s <code>inject</code> method.</p>
<p>One thing you&#8217;ll find at Ruby-doc.org is that as of Ruby 1.8.7 and later, <code>inject</code> gained a synonym: the more familiar term <code>reduce</code>.</p>
<p>As for <a href="http://www.ruby-doc.org/core-1.9/classes/Enumerable.html#M002971">the description of the <code>inject</code>/<code>reduce</code> method</a>, I don&#8217;t find it terribly helpful:</p>
<blockquote><p>
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.</p>
<p>If you specify a block, then for each element in enum&lt;i&gt; the block is passed an accumulator value (&lt;i&gt;memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value fo the method.</p>
<p>If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.
</p></blockquote>
<p>(Yes, those stray &lt;i&gt; tags are part of the text of the description for <code>inject</code>. Hopefully they&#8217;ll fix that soon.)</p>
<p>This confusing text becomes a little clearer with some examples. The most typical example of <code>inject</code>/<code>reduce</code>/<code>fold</code> in action is the classic &#8220;compute the sum of the numbers in this range or array&#8221; problem. There are a number of approaches you can take in Ruby, all of which use <code>inject</code>/<code>reduce</code>:<br />
<code>
<pre>
(1..8).reduce(:+)
=> 36

(1..8).reduce {|sum, number| sum += number}
=> 36

(1..8).reduce(0) {|sum, number| sum += number}
=> 36
</pre>
<p></code></p>
<p>The <code>reduce</code> method takes some kind of operation and applies it across the enumerable to yield a single result. In this case, the operation is addition. </p>
<p>Explaining <em>how</em> that operation is applied is a little trickier, but I do just that in the next section.</p>
<h3>Demonstrating inject / reduce / fold With a Piece of Paper and Literal Folding</h3>
<p>To explain what&#8217;s happening in the code above, I&#8217;m going to do use a piece of paper. I&#8217;ve folded it into 8 even sections and then numbered each section, as shown in the photo below:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_1.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>Think of the paper as the range <code>(1..8)</code>. We&#8217;re now going to compute the sum of the numbers in this range, step by step, using a literal <strong>fold</strong> &#8212; that is, by folding the paper. I&#8217;m going to start folding from the left side of the paper, and when I do, I&#8217;m going to add the numbers that I&#8217;m folding into each other.</p>
<p>In the first fold, I&#8217;m folding the number <strong>1</strong> onto the number <strong>2</strong>. Adding these two numbers yields <strong>3</strong>, which I write on the back of the fold:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_2.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>For the second fold, I fold the first number <strong>3</strong> onto the second number <strong>3</strong>. The sum of these two numbers is <strong>6</strong>, and I write that on the back of the resulting fold:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_3.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>I fold again: this time, it&#8217;s the number <strong>6</strong> onto the number <strong>4</strong>, the sum of which is <strong>10</strong>. I write that number down on the resulting fold:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_4.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>Next, I fold <strong>10</strong> onto <strong>5</strong>, yielding the number <strong>15</strong>:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_5.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>I then fold <strong>15</strong> onto <strong>6</strong>, which gives me <strong>21</strong>:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_6.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>Next comes <strong>21</strong> folded onto <strong>7</strong>, which makes for a sum of <strong>28</strong>:</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_7.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>And finally, <strong>28</strong> folded onto <strong>8</strong>, which gives us a final total of <strong>36</strong>.</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/fold_8.jpg" alt="" title="fold_1" width="500" height="375" /></p>
<p>And there you have it: a paper-based explanation of <code>inject</code>/<code>reduce</code>/<code>fold</code>, as well as why I often refer to the operation as &#8220;folding&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/09/03/enumerating-enumerable-a-cute-trick-for-explaining-inject-reduce-fold/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#group_by</title>
		<link>http://www.globalnerdy.com/2008/08/31/enumerating-enumerable-enumerablegroup_by/</link>
		<comments>http://www.globalnerdy.com/2008/08/31/enumerating-enumerable-enumerablegroup_by/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 20:52:02 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1392</guid>
		<description><![CDATA[
Once again, it&#8217;s Enumerating Enumerable time! This is the latest in my series of articles where I set out to make better documentation for Ruby&#8217;s Enumerable module than Ruby-Doc.org&#8217;s. In this installment &#8212; the seventeenth in the series &#8212; I cover the group_by method.
In case you missed any of the previous articles, they&#8217;re listed and [...]]]></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>Once again, it&#8217;s <strong><cite>Enumerating Enumerable</cite></strong> time! This is the latest in my series of articles where I set out to make better documentation for Ruby&#8217;s <code>Enumerable</code> module than Ruby-Doc.org&#8217;s. In this installment &#8212; the <em>seventeenth</em> in the series &#8212; I cover the <code>group_by</code> method.</p>
<p>In case you missed any of the previous 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>
<li><a href="http://www.globalnerdy.com/2008/08/01/enumerating-enumerable-enumerableeach_with_index/">each_with_index</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/02/enumerating-enumerable-enumerableentries-enumerableto_a/">entries / to_a</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/07/enumerating-enumerable-enumerablefind_all-enumerableselect/">find_all / select</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/14/enumerating-enumerable-enumerablefind_index/">find_index</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/15/enumerating-enumerable-enumerablefirst/">first</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/21/enumerating-enumerable-enumerablegrep/">grep</a></li>
</ol>
<h3>Enumerable#group_by Quick Summary</h3>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/ruby_enumerablegroup_by.jpg" alt="Graphic representation of the &quot;group_by&quot; method in Ruby&#039;s &quot;Enumerable&quot; module." title="Graphic representation of the &quot;group_by&quot; method in Ruby&#039;s &quot;Enumerable&quot; module." width="425" height="397" /></p>
<table border="1" cellspacing="0" cellpadding="5">
<tr>
<th>In the simplest possible terms</th>
<td>Break a collection into groups based on some given criteria.</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9 only</td>
</tr>
<tr>
<th>Expects</th>
<td>A block containing the criteria by which the items in the collection will be grouped.</td>
</tr>
<tr>
<th>Returns</th>
<td>A hash where each key represents a group. Each key&#8217;s corresponding value is an array containing the members of that group.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core-1.9/classes/Enumerable.html#M002974">Enumerable#group_by</a></td>
</tr>
</table>
<h3>Enumerable#group_by and Arrays</h3>
<p>When used on an array, <code>group_by</code> iterates through the array, passing each element to to the block. The result value of the block is the group into which the element will be placed.</p>
<h4>Example 1</h4>
<p>For the first example, I&#8217;ll use some code similar to the example given in Ruby-doc.org&#8217;s writeup of <code>group_by</code>:</p>
<p><code>
<pre>
(0..15).group_by {|number| number % 3}
=> {0=>[0, 3, 6, 9, 12, 15], 1=>[1, 4, 7, 10, 13], 2=>[2, 5, 8, 11, 14]}
</pre>
<p></code></p>
<p>In the code above, the numbers 0 through 15 are passed to the block, which receives each number as the parameter <code>number</code>. The group that each number is placed into is determined by the result value of the block, <code>number % 3</code>, whose result can be one of 0, 1 or 2. This means that:</p>
<ul>
<li>The resulting hash will have three groups, represented by the keys <code>0</code>, <code>1</code> and <code>2</code></li>
<li>The key <code>0</code>&#8217;s corresponding value is an array containing the numbers in the range (0..15) that are evenly divisible by 3 (i.e. the numbers for which <code>number % 3</code> is 0.</li>
<li>The key <code>1</code>&#8217;s corresponding value is an array containing the numbers in the range (0..15) that when divided by 3 leave a remainder of 1 (i.e. the numbers for which <code>number % 3</code> is 1.</li>
<li>The key <code>2</code>&#8217;s corresponding value is an array containing the numbers in the range (0..15) that when divided by 3 leave a remainder of 2 (i.e. the numbers for which <code>number % 3</code> is 2.</li>
</ul>
<h4>Example 2</h4>
<p>In the first example, the keys in the resulting hash are the same type as the values in the array whose contents we&#8217;re grouping. In this example, I&#8217;ll show that the keys in the resulting hash don&#8217;t have to be the same type as the values in the array.<br />
<code>
<pre>
simpsons = %w(Homer Marge Bart Lisa Abraham Herb)
=> ["Homer", "Marge", "Bart", "Lisa", "Abraham", "Herb"]

simpsons.group_by{|simpson| simpson.length}
=> {5=>["Homer", "Marge"], 4=>["Bart", "Lisa", "Herb"], 7=>["Abraham"]}
</pre>
<p></code></p>
<p>In the code above, each Simpson name is passed to the block, which receives it as the parameter <code>simpson</code>. The block&#8217;s result is the length of <code>simpson</code>, and this result is the group into which the name will go.</p>
<p>In the resulting hash:</p>
<ul>
<li>Note that the keys are integers while the names in the groups are strings.</li>
<li>The key <code>5</code>&#8217;s array contains those names in <code>Simpsons</code> that are 5<br />
characters in length.</li>
<li>The key <code>4</code>&#8217;s array contains those names in <code>Simpsons</code> that are 4 characters in length.</li>
<li>The key <code>7</code>&#8217;s array contains those names in <code>Simpsons</code> that are 7 characters in length.</li>
</ul>
<h4>Example 3</h4>
<p>In the previous two examples, the keys for the resulting array were calculated from the values in the initial array. In this example, I&#8217;ll demonstrate that the keys for the groupings can be determined in a completely arbitrary fashion that has nothing to do with the values:</p>
<p><code>
<pre>
# Put the Simpsons into randomly determined groups
simpsons.group_by{rand(3) + 1}
=> {3=>["Homer", "Bart", "Abraham", "Herb"], 1=>["Marge", "Lisa"]}

# Let's try that again. The results are very likely to be different:
simpsons.group_by{rand(3) + 1}
=> {1=>["Homer", "Bart"], 2=>["Marge", "Lisa", "Herb"], 3=>["Abraham"]}

# One more time!
simpsons.group_by{rand(3) + 1}
=> {2=>["Homer", "Bart", "Lisa"], 3=>["Marge", "Herb"], 1=>["Abraham"]}
</pre>
<p></code></p>
<h3>Enumerable#group_by and Hashes</h3>
<p>When used on a hash, <code>group_by</code> passes each key/value pair in the hash to the block, which you can “catch” as either:</p>
<p>   1. A two-element array, with the key as element 0 and its corresponding value as element 1, or<br />
   2. Two separate items, with the key as the first item and its corresponding value as the second item.</p>
<h4>Example 1</h4>
<p>In this example, we&#8217;ll group the cast of <cite>Family Guy</cite> by the item that they&#8217;re bringing to a potluck dinner:<br />
<code>
<pre>
potluck = {"Peter" => "lasagna",
           "Lois"  => "potato salad",
           "Chris" => "lasagna",
           "Meg"   => "brownies",
           "Stewie" => "chateaubriand",
           "Brian" => "potato salad",
           "Evil Monkey" => "potato salad"}
=> {"Peter"=>"lasagna", "Lois"=>"potato salad", "Chris"=>"lasagna", "Meg"=>"brownies",
"Stewie"=>"chateaubriand", "Brian"=>"potato salad", "Evil Monkey"=>"potato salad"}

# Here's one way to do it:
potluck.group_by{|person, bringing| bringing}
=> {"lasagna"=>[["Peter", "lasagna"], ["Chris", "lasagna"]], "potato salad"=>[["Lois", "potato salad"],
["Brian", "potato salad"], ["Evil Monkey", "potato salad"]], "brownies"=>[["Meg", "brownies"]],
"chateaubriand"=>[["Stewie", "chateaubriand"]]}

# Here's another way to do it:
potluck.group_by{|person| person[1]}
=> {"lasagna"=>[["Peter", "lasagna"], ["Chris", "lasagna"]], "potato salad"=>[["Lois", "potato salad"],
["Brian", "potato salad"], ["Evil Monkey", "potato salad"]], "brownies"=>[["Meg", "brownies"]],
"chateaubriand"=>[["Stewie", "chateaubriand"]]}
</pre>
<p></code></p>
<h4>Example 2</h4>
<p>In the previous example, the groupings were based on a calculation performed on the objects in the original hash. In this example, the groupings will be random: a random number generator will determine whose car each potluck attendee will ride to the potluck dinner:</p>
<p><code>
<pre>
potluck.group_by {[:peters_car, :quagmires_car, :clevelands_car][rand(3)]}
=> {:peters_car=>[["Peter", "lasagna"], ["Chris", "lasagna"], ["Evil Monkey", "potato salad"]],
:quagmires_car=>[["Lois", "potato salad"], ["Meg", "brownies"], ["Stewie", "chateaubriand"]],
:clevelands_car=>[["Brian", "potato salad"]]}

# Let's try another random grouping
potluck.group_by {[:peters_car, :quagmires_car, :clevelands_car][rand(3)]}
=> {:peters_car=>[["Peter", "lasagna"], ["Meg", "brownies"]], :quagmires_car=>[["Lois", "potato salad"],
["Stewie", "chateaubriand"], ["Brian", "potato salad"], ["Evil Monkey", "potato salad"]],
:clevelands_car=>[["Chris", "lasagna"]]}

# One more time!
potluck.group_by {[:peters_car, :quagmires_car, :clevelands_car][rand(3)]}
=> {:peters_car=>[["Peter", "lasagna"], ["Chris", "lasagna"], ["Stewie", "chateaubriand"]],
:quagmires_car=>[["Lois", "potato salad"], ["Evil Monkey", "potato salad"]], :clevelands_car=>[["Meg", "brownies"],
["Brian", "potato salad"]]}
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/31/enumerating-enumerable-enumerablegroup_by/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#first</title>
		<link>http://www.globalnerdy.com/2008/08/15/enumerating-enumerable-enumerablefirst/</link>
		<comments>http://www.globalnerdy.com/2008/08/15/enumerating-enumerable-enumerablefirst/#comments</comments>
		<pubDate>Fri, 15 Aug 2008 04:39:56 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[first]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1238</guid>
		<description><![CDATA[
Welcome to another installment of Enumerating Enumerable, my series of articles in I attempt to do a better job of documenting Ruby&#8217;s Enumerable module than Ruby-Doc.org. In this installment, I cover the first method.
In case you missed any of the previous articles, they&#8217;re listed and linked below:

all?
any?
collect / map
count
cycle
detect / find
drop
drop_while
each_cons
each_slice
each_with_index
entries / to_a
find_all / select
find_index

Enumerable#first [...]]]></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>Welcome to another installment of <strong><cite>Enumerating Enumerable</cite></strong>, my series of articles in I attempt to do a better job of documenting Ruby&#8217;s <code>Enumerable</code> module than Ruby-Doc.org. In this installment, I cover the <code>first</code> method.</p>
<p>In case you missed any of the previous 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>
<li><a href="http://www.globalnerdy.com/2008/08/01/enumerating-enumerable-enumerableeach_with_index/">each_with_index</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/02/enumerating-enumerable-enumerableentries-enumerableto_a/">entries / to_a</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/07/enumerating-enumerable-enumerablefind_all-enumerableselect/">find_all / select</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/14/enumerating-enumerable-enumerablefind_index/">find_index</a></li>
</ol>
<h3>Enumerable#first Quick Summary</h3>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/ruby_enumerablefirst.jpg" alt="Graphic representing the &quot;first&quot; method in Ruby&#039;s &quot;Enumerable&quot; module" title="Graphic representing the &quot;first&quot; method in Ruby&#039;s &quot;Enumerable&quot; module" width="329" height="244" /></p>
<table border="1" cellspacing="0" cellpadding="5">
<tr>
<th>In the simplest possible terms</th>
<td>What are the first <em>n</em> items 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 integer <em>n</em> that specifies the first <em>n</em> items of the collection to return. If this integer is not given, <em>n</em> is 1 by default.</td>
</tr>
<tr>
<th>Returns</th>
<td>If <code>first</code> is applied to a collection containing <em>m</em> elements:</p>
<ul>
<li>The first item in the collection, if <em>m</em> > 0 and no argument <em>n</em> is provided.</li>
<li>An array containing the first <em>n</em> items in the collection, if <em>m</em> > 0 and an argument <em>n</em> is provided.</li>
<li><code>nil</code> if the collection is empty and no argument <em>n</em> is provided.</li>
<li>The empty array <code>[]</code> if the collection is empty and an argument <em>n</em> is provided.</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#M002975">Enumerable#first</a></td>
</tr>
</table>
<h3>Enumerable#first and Arrays</h3>
<p>When used on an array without an argument, <code>first</code> returns the first item in the array:<br />
<code>
<pre>
posts = ["First post!", "Second post!", "Third post!"]
=> ["First post!", "Second post!", "Third post!"]

# What's the first item in posts?
posts.first
=> "First post!"

# Here's the equivalent using array notation:
posts[0]
=> "First post!"
</pre>
<p></code></p>
<p>When used on an array with an integer argument <em>n</em>, <code>first</code> returns an array containing the first <em>n</em> items in the original array:<br />
<code>
<pre>
# What are the first 2 items in posts?
posts.first 2
=> ["First post!", "Second post!"]

# Note that when you provide an argument of 1,
# the result is still an array -- with just one element.
# If you want a scalar, don't use an argument.
posts.first 1
=> ["First post!"]

# Here's the equivalent using array slice notation:
posts[0..1]
=> ["First post!", "Second post!"]

posts[0...2]
=> ["First post!", "Second post!"]
</pre>
<p></code></p>
<p>When used on an empty array, <code>first</code> returns:</p>
<ul>
<li><code>nil</code> if no argument <em>n</em> is provided</li>
<li>The empty array, <code>[]</code>, if an argument <em>n</em> is provided</li>
</ul>
<p><code>
<pre>
[].first
=> nil

[].first 2
=> []
</pre>
<p></code></p>
<h3>Enumerable#first and Hashes</h3>
<p>In Ruby 1.8 and previous versions, hash order is seemingly arbitrary. Starting with Ruby 1.9, hashes retain the order in which they were defined, which makes the <code>first</code> method a little more applicable.</p>
<p>When used on a hash without an argument, <code>first</code> returns the first item in the hash as a two-element array, with the key as the first element and the corresponding value as the second element.<br />
<code>
<pre>
# Let's see what stages of partying our friends are in
party_stages = {"Alice" => :party_mineral,
                "Bob"   => :party_animal,
                "Carol" => :party_reptile,
                "Dave"  => :party_vegetable}
=> {"Alice"=>:party_mineral, "Bob"=>:party_animal, "Carol"=>:party_reptile, "Dave"=>:party_vegetable}

# Who's the first partier and what state is s/he in?
party_stages.first
=> ["Alice", :party_mineral]
</pre>
<p></code></p>
<p>When used on a hash with an integer argument <em>n</em>, <code>first</code> returns an array containing the first <em>n</em> items in the hash, with each item represented as a two-element array:<br />
<code>
<pre>
party_stages.first 2
=> [["Alice", :party_mineral], ["Bob", :party_animal]]

# Note that when you provide an argument of 1,
# the result is still an array -- with just one element.
# If you want a scalar, don't use an argument.
party_stages.first 1
=> [["Alice", :party_mineral]]
</pre>
<p></code></p>
<p>When used on an empty hash, <code>first</code> returns:</p>
<ul>
<li><code>nil</code> if no argument <em>n</em> is provided</li>
<li>The empty array, <code>[]</code>, if an argument <em>n</em> is provided</li>
</ul>
<p><code>
<pre>
{}.first
=> nil

{}.first 2
=> []
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/15/enumerating-enumerable-enumerablefirst/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#find_index</title>
		<link>http://www.globalnerdy.com/2008/08/14/enumerating-enumerable-enumerablefind_index/</link>
		<comments>http://www.globalnerdy.com/2008/08/14/enumerating-enumerable-enumerablefind_index/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 15:54:14 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Enumerating Enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1207</guid>
		<description><![CDATA[
Once again, it&#8217;s Enumerating Enumerable, my series of articles in which I attempt to outdo Ruby-Doc.org&#8217;s documentation of Ruby&#8217;s Enumerable module. In this article, I cover the find_index method, which was introduced in Ruby 1.9.
In case you missed any of the previous articles, they&#8217;re listed and linked below:

all?
any?
collect / map
count
cycle
detect / find
drop
drop_while
each_cons
each_slice
each_with_index
entries / to_a
find_all / [...]]]></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>Once again, it&#8217;s <strong><cite>Enumerating Enumerable</cite></strong>, my series of articles in which I attempt to outdo Ruby-Doc.org&#8217;s documentation of Ruby&#8217;s <code>Enumerable</code> module. In this article, I cover the <code>find_index</code> method, which was introduced in Ruby 1.9.</p>
<p>In case you missed any of the previous 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>
<li><a href="http://www.globalnerdy.com/2008/08/01/enumerating-enumerable-enumerableeach_with_index/">each_with_index</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/02/enumerating-enumerable-enumerableentries-enumerableto_a/">entries / to_a</a></li>
<li><a href="http://www.globalnerdy.com/2008/08/07/enumerating-enumerable-enumerablefind_all-enumerableselect/">find_all / select</a></li>
</ol>
<h3>Enumerable#find_index Quick Summary</h3>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/ruby_enumerablefind_index.jpg" alt="Graphic representation of the &quot;find_index&quot; method in Ruby&#039;s &quot;Enumerable&quot; module" title="Graphic representation of the &quot;find_index&quot; method in Ruby&#039;s &quot;Enumerable&quot; module" width="323" height="226" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>What&#8217;s the index of the first item in the collection that meets the given criteria?</td>
</tr>
<tr>
<th>Ruby version</th>
<td>1.9</td>
</tr>
<tr>
<th>Expects</th>
<td>A block containing the criteria.</td>
</tr>
<tr>
<th>Returns</th>
<td>
<ul>
<li>The index of the item in the collection that matches the criteria, if there is one.</li>
<li><code>nil</code>, if no item in the collection matches the crtieria.</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#M002965">Enumerable#find_index</a></td>
</tr>
</table>
<h3>Enumerable#find_index and Arrays</h3>
<p>When used on an array, <code>find_index</code> passes each item in the array to the given block and either:</p>
<ul>
<li>Stops when the current item causes the block to return a value that evaluates to <code>true</code> (that is, anything that isn&#8217;t <code>false</code> or <code>nil</code>) and returns the index of that item, or</li>
<li>Returns <code>nil</code> if there is no item in the array that causes the block to return a value that evaluates to <code>true</code>.</li>
</ul>
<p>Some examples:<br />
<code>
<pre>
# How about an array of the name of the first cosmonauts and astronauts,
# listed in the chronological order of the missions?
mission_leaders = ["Gagarin", "Shepard", "Grissom", "Titov", "Glenn", "Carpenter",
"Nikolayev", "Popovich"]
=> ["Gagarin", "Shepard", "Grissom", "Titov", "Glenn", "Carpenter", "Nikolayev",
"Popovich"]

# Yuri Gagarin was the first in space
mission_leaders.find_index{|leader| leader == "Gagarin"}
=> 0

# John Glenn was the fifth
mission_leaders.find_index{|leader| leader == "Glenn"}
=> 4

# And James Tiberius Kirk is not listed in the array
kirk_present = mission_leaders.find_index{|leader| leader == "Kirk"}
=> nil
</pre>
<p></code></p>
<h3>Enumerable#find_index and Hashes</h3>
<p>When used on a hash, <code>find_index</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>As with arrays, <code>find_index</code>:</p>
<ul>
<li>Stops when the current item causes the block to return a value that evaluates to <code>true</code> (that is, anything that isn&#8217;t <code>false</code> or <code>nil</code>) and returns the index of that item, or</li>
<li>Returns <code>nil</code> if there is no item in the array that causes the block to return a value that evaluates to <code>true</code>.</li>
</ul>
<p>Some examples:<br />
<code>
<pre>
require 'date'
=> true

# These are the names of the first manned spaceships and their launch dates
launch_dates = {"Kedr"              => Date.new(1961, 4, 12),
                "Freedom 7"         => Date.new(1961, 5, 5),
                "Liberty Bell 7"    => Date.new(1961, 7, 21),
                "Orel"              => Date.new(1961, 8, 6),
                "Friendship 7"      => Date.new(1962, 2, 20),
                "Aurora 7"          => Date.new(1962, 5, 24),
                "Sokol"             => Date.new(1962, 8, 11),
                "Berkut"            => Date.new(1962, 8, 12)}
=> {"Kedr"=>#&lt;Date: 4874803/2,0,2299161&gt;, "Freedom 7"=&gt;#&lt;Date: 4874849/2,0,2299161&gt;,
"Liberty Bell 7"=&gt;#&lt;Date: 4875003/2,0,2299161&gt;, "Orel"=&gt;#&lt;Date: 4875035/2,0,2299161&gt;,
"Friendship 7"=&gt;#&lt;Date: 4875431/2,0,2299161&gt;, "Aurora 7"=&gt;#&lt;Date: 4875617/2,0,2299161&gt;,
"Sokol"=&gt;#&lt;Date: 4875775/2,0,2299161&gt;, "Berkut"=&gt;#&lt;Date: 4875777/2,0,2299161&gt;}

# Where in the list is John Glenn's ship, the Friendship 7?
launch_dates.find_index{|ship, date| ship == "Friendship 7"}
=> 4

# Where in the list is the first mission launched in August 1962?
launch_dates.find_index{|ship, date| date.year == 1962 &#038;&#038; date.month == 8}
=> 6

# The same thing, expressed a little differently
launch_dates.find_index{|launch| launch[1].year == 1962 &#038;&#038; launch[1].month == 8}
=> 6
</pre>
<p></code></p>
<h3>Using find_index as a Membership Test</h3>
<p>Although <code>Enumerable</code> has a method for checking whether an item is a member of a collection (the <code>include?</code> method and its synonym, <code>member?</code>), <code>find_index</code> is a more powerful membership test for two reasons:</p>
<ol>
<li><code>include?</code>/<code>member?</code> only check membership by using the <code>==</code> operator, while <code>find_index</code> lets you define a block to set up all sorts of tests. <code>include?</code>/<code>member?</code> asks &#8220;Is there an object X in the collection equal to my object Y?&#8221; while <code>find_index</code> can be used to ask &#8220;Is there an object X in the collection that matches these criteria?&#8221;</li>
<li><code>include?</code>/<code>member?</code> returns <code>true</code> if there is an object X in the collection that is equal to the given object Y. <code>find_index</code> goes one step further: not only can it be used to report the equivalent of <code>true</code> if there is an object X in the collection that is equal to the given object Y, it also reports its location in the collection.</li>
</ol>
<p>A quick example of this use in action:<br />
<code>
<pre>
# Once again, the mission leaders
mission_leaders = ["Gagarin", "Shepard", "Grissom", "Titov", "Glenn", "Carpenter",
"Nikolayev", "Popovich"]
=> ["Gagarin", "Shepard", "Grissom", "Titov", "Glenn", "Carpenter", "Nikolayev",
 "Popovich"]

# Yuri Gagarin is in the list
gagarin_in_list = mission_leaders.find_index {|leader| leader == "Gagarin"}
=> 0

# Captain James T. Kirk is not
kirk_in_list = mission_leaders.find_index {|leader| leader == "Kirk"}
=> nil

# gagarin_in_list is 0, which as a non-false and non-nil value evaluates as true.
# We can use it as both a membership test *and* as his location in the list.
p "Gagarin's there. He's number #{gagarin_in_list + 1} in the list." if gagarin_in_list
"Gagarin's there. He's number 1 in the list."
=> "Gagarin's there. He's number 1 in the list."

# kirk_in_list is nil, which is one of Ruby's two "false" values.
# Let's use it with the "something OR something else" idiom that
# many Ruby programmers like.
kirk_in_list || (p "You only *think* he wasn't there.")
"You only *think* he wasn't there."
=> "You only *think* he wasn't there."
</pre>
<p></code></p>
<h3>Parts that Haven&#8217;t Been Implemented Yet</h3>
<p>Ruby-Doc.org&#8217;s documentation is generated from the comments in the C implementation of Ruby. It mentions a way of calling <code>find_index</code> that is just like calling <code>include?</code>/<code>member?</code>:<br />
<code>
<pre>
# What the docs say (does not work yet!)
["Alice", "Bob", "Carol"].find_index("Bob")
=> 1

# What happens with the current version of Ruby 1.9
["Alice", "Bob", "Carol"].find_index("Bob")
ArgumentError: wrong number of arguments(1 for 0)
...
</pre>
<p></code><br />
Ruby 1.9 is considered to be a work in progress, so I suppose it&#8217;ll get implemented in a later release.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/14/enumerating-enumerable-enumerablefind_index/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#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#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>
	</channel>
</rss>
