<?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"
	>

<channel>
	<title>Global Nerdy &#187; Programming</title>
	<atom:link href="http://globalnerdy.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.globalnerdy.com</link>
	<description>Joey deVilla's blog on nerdy life, work and play</description>
	<pubDate>Tue, 14 Oct 2008 03:44:36 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.2</generator>
	<language>en</language>
			<item>
		<title>The Manga Guide to Databases</title>
		<link>http://www.globalnerdy.com/2008/10/08/the-manga-guide-to-databases/</link>
		<comments>http://www.globalnerdy.com/2008/10/08/the-manga-guide-to-databases/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 02:47:58 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[books]]></category>

		<category><![CDATA[Databases]]></category>

		<category><![CDATA[manga]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1721</guid>
		<description><![CDATA[Maybe we&#8217;re seeing the start of a strange new manga trend in books. First came The Adventures of Johnny Bunko: The Last Career Guide You&#8217;ll Ever Need, and now there&#8217;s The Manga Guide to Databases:

Here&#8217;s the publisher&#8217;s write-up of the book:

Want to learn about databases without the tedium? With its unique combination of Japanese-style comics [...]]]></description>
			<content:encoded><![CDATA[<p>Maybe we&#8217;re seeing the start of a strange new <em>manga</em> trend in books. First came <a href="http://www.amazon.com/Adventures-Johnny-Bunko-Career-Guide/dp/1594482918?ie=UTF8&#038;s=books&#038;qid=1210166042&#038;sr=8-1"><cite>The Adventures of Johnny Bunko: The Last Career Guide You&#8217;ll Ever Need</cite></a>, and now there&#8217;s <a href="http://www.amazon.com/gp/product/1593271905"><strong><cite>The Manga Guide to Databases</cite></strong></a>:</p>
<p style="text-align:center;"><a href="http://www.amazon.com/gp/product/1593271905"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/10/the_manga_guide_to_databases.jpg" alt="Cover of &quot;The Manga Guide to Databases&quot;" title="Cover of &quot;The Manga Guide to Databases&quot;" width="380" height="500" /></a></p>
<p>Here&#8217;s the publisher&#8217;s write-up of the book:</p>
<blockquote><p>
Want to learn about databases without the tedium? With its unique combination of Japanese-style comics and serious educational content, The Manga Guide to Databases is just the book for you.</p>
<p>Princess Ruruna is stressed out. With the king and queen away, she has to manage the Kingdom of Kod&#8217;s humongous fruit-selling empire. Overseas departments, scads of inventory, conflicting prices, and so many customers! It&#8217;s all such a confusing mess. But a mysterious book and a helpful fairy promise to solve her organizational problems—with the practical magic of databases.</p>
<p>In The Manga Guide to Databases, Tico the fairy teaches the Princess how to simplify her data management. We follow along as they design a relational database, understand the entity-relationship model, perform basic database operations, and delve into more advanced topics. Once the Princess is familiar with transactions and basic SQL statements, she can keep her data timely and accurate for the entire kingdom. Finally, Tico explains ways to make the database more efficient and secure, and they discuss methods for concurrency and replication.</p>
<p>Examples and exercises (with answer keys) help you learn, and an appendix of frequently used SQL statements gives the tools you need to create and maintain full-featured databases.</p>
<p>(Of course, it wouldn&#8217;t be a royal kingdom without some drama, so read on to find out who gets the girl—the arrogant prince or the humble servant.)</p>
<p>This EduManga book is a translation of a bestselling series in Japan, co-published with Ohmsha, Ltd., of Tokyo, Japan.
</p></blockquote>
<p>The book will be available on December 1st, just in time to order as a Christmas present for someone who&#8217;s into both programming and manga.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/10/08/the-manga-guide-to-databases/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Apple Drops iPhone NDA</title>
		<link>http://www.globalnerdy.com/2008/10/02/apple-drops-iphone-nda/</link>
		<comments>http://www.globalnerdy.com/2008/10/02/apple-drops-iphone-nda/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 04:45:36 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Apple]]></category>

		<category><![CDATA[iPhone]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[NDA]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1661</guid>
		<description><![CDATA[Image from Wikimedia Commons.
On the off-chance you hadn&#8217;t yet heard, Apple has finally dropped its much-reviled NDA for iPhone developers for released software. It was so restrictive that developers were forbidden from discussing or writing documentation on iPhone development, even with or for other iPhone developers.
In the announcement on Apple Developer Connection, they explain why [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://en.wikipedia.org/wiki/Image:Ball_gag1.jpg"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/10/apple_ball_gag.jpg" alt="Woman wearing ball gag with Apple logo" title="Woman wearing ball gag with Apple logo" width="250" height="349" /></a><br /><span class="caption">Image from Wikimedia Commons.</span></p>
<p>On the off-chance you hadn&#8217;t yet heard, <a href="http://developer.apple.com/iphone/program/"><strong>Apple has finally dropped its much-reviled NDA for iPhone developers for released software.</strong></a> It was so restrictive that developers were forbidden from discussing or writing documentation on iPhone development, even with or for other iPhone developers.</p>
<p>In <a href="http://developer.apple.com/iphone/program/">the announcement on Apple Developer Connection</a>, they explain why they put developers under the excessively-restrictive NDA:</p>
<blockquote><p>
We put the NDA in place because the iPhone OS includes many Apple inventions and innovations that we would like to protect, so that others don’t steal our work. It has happened before. While we have filed for hundreds of patents on iPhone technology, the NDA added yet another level of protection. We put it in place as one more way to help protect the iPhone from being ripped off by others.
</p></blockquote>
<p>This sort of behaviour harkens back to the 1990s, when Apple behaved as if all third-party developers who weren&#8217;t Adobe existed on a spectrum ranging from &#8220;unwanted houseguest&#8221; to &#8220;the enemy&#8221;. Speaking as a guy with a strong technical evangelist background (<em>note to employers: hint, hint!</em>), this is not the way you foster developer love nor build a developer community.</p>
<p>Expect iPhone development tutorials and tips to start popping up all over the web and for the Pragmatic Programmers&#8217; book <a href="http://www.pragprog.com/titles/amiphd/iphone-sdk-development"><cite>iPhone SDK Development</cite></a> to finally see the light of day.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/10/02/apple-drops-iphone-nda/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Notes from Ruby on Rails Project Night</title>
		<link>http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/</link>
		<comments>http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 21:37:50 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Meetups]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Toronto]]></category>

		<category><![CDATA[Creative]]></category>

		<category><![CDATA[Rails]]></category>

		<category><![CDATA[Rich Media Institute]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[Ruby/Rails Project Night]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1567</guid>
		<description><![CDATA[It&#8217;s Back!
Last Friday marked the return of Ruby on Rails Project Night, a Toronto-based event where developers who worked on Ruby and Rails projects could do in-depth presentations on their current projects or ideas. It was on hiatus for the past couple of months (you can see this entry for the definition of &#8220;on hiatus&#8221;), [...]]]></description>
			<content:encoded><![CDATA[<h3>It&#8217;s Back!</h3>
<p><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/bruce_lee_rails_nunchucks.jpg" alt="Bruce Lee, brandishing &quot;Rails&quot; nunchucks" title="Bruce Lee, brandishing &quot;Rails&quot; nunchucks" width="270" height="200" align="right" />Last Friday marked the return of <strong>Ruby on Rails Project Night</strong>, a Toronto-based event where developers who worked on Ruby and Rails projects could do in-depth presentations on their current projects or ideas. It was on hiatus for the past couple of months (you can see <a href="http://www.globalnerdy.com/2008/09/17/the-return-of-ruby-on-rails-project-night/">this entry</a> for the definition of &#8220;on hiatus&#8221;), but thanks to the efforts of <a href="http://correlations.wordpress.com/"><strong>Corina Newby</strong></a>, who helped put together the event at its old venue, it&#8217;s back, and judging from the attendance, it was missed. Thanks, Corina, for all your work!</p>
<h3>James Robertson</h3>
<p>The first speaker was also the special guest (and the reason the event was held on a Friday, as opposed to the typical Monday or Tuesday): <a href="http://www.cincomsmalltalk.com/blog/blogView?content=bio"><strong>James Robertson</strong></a>, whom you may know from his blog <a href="http://www.cincomsmalltalk.com/blog/blogView"><cite>Smalltalk Tidbits, Industry Rants</cite></a>. He was on a &#8220;Canadian tour&#8221;, during which he was talking about the Smalltalk-based web app framework <a href="http://en.wikipedia.org/wiki/Seaside_(software)">Seaside</a> as well as Webvelocity, which puts the Smalltalk development experience within the browser.</p>
<p>Here&#8217;s the abstract for his presentation (<a href="http://correlations.wordpress.com/2008/09/19/update-for-tonight-toronto-ror-project-night-returns/">from this entry from Corina&#8217;s blog</a>):</p>
<blockquote><p>
WebVelocity is a new Smalltalk Development Environment that is oriented around Seaside for Web Development and Glorp for Object/Relatonal Mapping. Come and see how WebVelocity re-targets the Smalltalk development experience into the Web Browser and simplifies the challenge of learning a new environment for newcomers. We’ll even build an entire application using Active Record and Scaffolding during the presentation, with minimal programming. If you’re a fan of Ruby on Rails, you need to come out and see this presentation!
</p></blockquote>
<p>Here are my notes from his presentation:</p>
<pre>
- Seaside is open source, but Smalltalk ain't
- Seaside is maintained in Squeak, which you could call "the open source Smalltalk"

- Ruby on Rails is opinionated
- "Seaside is also opinated; it just has different opinions"
- When building Seaside, Avi Bryant asked "What if I took all the assumptions about web apps...
  and ignored them?"
- Some of what I show you is what happens when you blow those assumptions

- The canonical Seaside example -- the number increment/decrement button
  (now we know where that disastrous DemoCamp Seaside presentation came from!)
- Seaside uses continuations to remember state
- They enable "proper" support for the backbutton
- Session state info is keyed via a cryptographically secure key in the URL

- With Rails, you're dealing with two different worlds: templates and code
- Seaside is just one world: You don't write any HTML at all, you write all Smalltalk
- It's all in one place
- Support for debugger -- you can debug web apps as if they were desktop apps, with breakpoints and resumes
- In Seaside, the "html" argument is a "brush" that knows how to "paint" HTML
- You can debug in the middle of a page hit

- In beta: Seaside totally within the browser
- Editing code within a webpage, including tooltips and color hinting
- Every time a method is entered and it is syntactically correct, it is auto-saved -- no need to manual save!
- [Shows a Smalltalk debugger with an Ajax front end]
- "In some ways, it's even more productive than the real Smalltalk environment is"
- [Smalltalk console within the browser]
- [Auto-indenting within the browser]
- [Auto-generates a scaffolding-like page]
- The "call" method lets you write web app code very much like writing GUI stuff
</pre>
<h3>Paul Doerwald</h3>
<p>The second speaker was <a href="http://pauldoerwald.ca/"><strong>Paul Doerwald</strong></a>, who changed his topic from the more Ruby/Rails-specific &#8220;insights gained from working with ActiveRecord validation&#8221; to a more general (but still interesting) topic: Agile Documentation. He figured that it might be a better fit with James&#8217; presentation, and it was &#8212; it was also quite interesting.</p>
<p>Here&#8217;s the abstract for his presentation:</p>
<blockquote><p>
“Programmers generally hate writing documentation. That’s because most documentation is kept separate from the code and becomes hard to keep up-to-date. Besides violating the DRY principle… it can lead to misleading documentation, which is generally worse than none at all.” [Subramaniam/Hunt '06]. Why do developers hate writing documentation, and why do stakeholders and managers keep requiring it? Is there agile documentation beyond inline API documentation (JavaDoc, RDoc, etc.) and comments in the code? What parts of a project deserve separate-from-code documentation? How do we identify them, capture them, and keep them relevant?</p>
<p>Tonight’s Toronto Ruby on Rails Project Night presentation discusses the problem of documentation, explores some key aspects to consider when writing effective  documentation, and dreams of a future of testable, executable documentation, where non-code knowledge could be integrated into your code.“
</p></blockquote>
<p>And here are my notes from his talk:</p>
<pre>
- My original presentation was going to be about insights gained from ActiveRecord validation
- But I've decided to change it -- it's now on Agile Documentation
- It's my M.Sc. Thesis!
- "You'll find this talk a bit heavy on problem and not so heavy on solution"
- Think of this as an introduction -- I want to frame things and ask:
  what is Agile Documentation?

- By "documentation", I mean by the kind that's by programmers for programmers

- It's not a particularly sexy area
- Frameworks are sexy:
    - Rails is sexy
    - Django is sexy
    - CakePHP is sexy...(for PHP)
- Languages are sexy
    - Ruby is sexy
    - Objective-C is..."strangely alluring"
- Even databases are sexy! Consider CouchDB and AWS
- What's not sexy?
    - Documentation
    - Backup -- at least not until Apple's Time Machine
    - Both are viewed as a waste of time

- We're developers. We may grudgingly accept the presence of non-developer things,
  but we don't want to do them
- Documentation is hard to write
- It seems so much easier to program rather than write
- Writing -- the non code-type -- is not our core competency
- We say "Our code is the authoritative documentation!"
- Consider what DHH said in a "Signal vs. Noise" blog entry in February 2006
    - When asked "How do you document your projects?", he replied "We don't."
    - He also said:
        - "Never worked consistently or successfully"
        - "Not necessary for our work"
        - "Most Rails developers can walk in and find out"
        - "We use Ruby"
        - "Method docs only for non-obvious behaviour"
        - "Docs mean BDUF"
        - "Appropriate only for onerous enviroments with complex policies"
        - "Focus on code quality instead"

- Like backups, docs are important
- We're not the only people who'll be working on a project, especially if it's a success
- We don't want to feel like we're wasting time when we're working
- Running a documentation tool and taking its output and pasting it into a Word doc is not DRY
- Why are we writing highly-coupled docs?

- Is there such a thing as agile documentation? I'm going to say yes
- Look at the Agile Manifesto
    - "We value working software over comprehensive documentation"
    - But it doesn't say that comprehensive documentation isn't valued!

- What's the state of the Art
    - For API Documentation, it's JavaDoc
    - In Rails, the outer classes are well documented, but not the inner ones
    - The JDK is extremely well-documented
    - You could say that RSpec is a form of agile documentation
    - It's a stretch, but Domain-Specific Languages could also be agile documentation
    - After all these, I can only think of process
    - When do we do docs? At the beginning of the process? At the end?

- What could agile documentation look like? What does it feel like?
- I borrowed principle from Alastair Cockburn's "Agile Software Development:
  The Cooperative Game, 2nd ed."
- The goals set out in the book:
    - Finish the game (i.e. finish development and launch the product)
    - Set up the game for the next team
    - Think of pool: maybe you take the hard shot first to set yourself up later for the easy shot
    - Coburn calls this "residue": the stuff that one team leaves behind for the next team
    - Residue includes:
        - Code
        - Process in place
        - Documentation

- I would argue that DHH/37signals has an oral form of documentation
- It works if the company doesn't grow too quickly
- What are we really asking for when we ask for the documentation: Tacit Knowledge
    - "That which is seen but not noticed"
    - It is information that is understood and implied but not stated
    - If you've ever brought someone else onto a team, you spend a lot of time
      explaining things that are obvious to you
    - You might not explain that stuff if you're doing it on paper
    - You don't want to end up in a situtation where there's too much documentation

- What can we borrow from software engineering principles?
    - Orthogonality
        - A good thing in software development
        - Intersect at a clear and obvious point and do not influence each other at any other point
    - Cohesion
        - All attributes and methods are related to the essence of the class
        - Don't have people look in 5 different places to get the answer to a single question
    - Coupling
        - The extent to which one thing is dependent on each other

- To the future
    - 5 years ago, unit testing was unheard of in the web development world
    - Rails and similar projects have helped popularize unit testing
    - We've moved from the point to where we say "testing is awesome"
    - Testing is now a core value
    - Can we make documentation a core value?

- Agile documentation processes
    - Large companies are good at this; open source people not so good
    - Looking to Rails:
        - Documentaton conventions?
        - What if we had 5 steps for writing documentation that did 70% of the work?
    - Can we integrate documentation with code?
        - In many cases, the docs exist as a Word document
        - A step up is to use a Wiki -- support for multiple authors, versioning, linking
        - Can we put docs right in the codebase?
        - Every Rails app has a doc directory -- can we use that?
        - We test code -- is there a way to make testable documentation?
        - What if we could tag a method and class with a keyword and make that keyword appear in the docs?
          -- We could generate an alert when changes happen
</pre>
<h3>Checking Out the Rich Media Institute</h3>
<p>After the presentation, which was held in the Rich Media Institute&#8217;s basement-level lecture room, a number of us headed upstairs to check out its main floor. If you&#8217;re a techie with a creative bent, this place is like a candy store. The front part is a store full of books, t-shirts, music and other goodies that new media creators and aficionados would love, while the back is a gallery for local interactive artists&#8217; works.</p>
<p>I took some photos of the place and posted them in the gallery below. Click on any of the thumbnails to see a larger version of the picture:<br />

<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/toy_soldier_candle_holder/' title='&quot;Toy Soldier&quot; Candle Holder'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/toy_soldier_candle_holder-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/store_wide_2/' title='A wide shot of the &quot;store&quot; part of the Rich Media Institute, taken from the front'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/store_wide_2-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/store_wide/' title='A wide shot of the &quot;store&quot; part of the Rich Media Institute, taken from the back.'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/store_wide-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/robot/' title='Cardboard robot in the &quot;gallery&quot; part of the Rich Media Institute'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/robot-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/interact_or_die/' title='&quot;Interact or Die!&quot;'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/interact_or_die-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/far_from_equilibrium/' title='&quot;Far from Equilibrium: Essays on Technology and Design Culture&quot;'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/far_from_equilibrium-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/discs_2/' title='Another shot of the music area of the Rich Media Institute&#039;s &quot;store&quot; section'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/discs_2-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/discs/' title='The music area of the Rich Media Institute&#039;s &quot;store&quot; section'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/discs-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/books_2/' title='Some of the books available at the Rich Media Institute&#039;s &quot;store&quot; section'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/books_2-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
<a href='http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/books/' title='The Tech Bookshelf at the Rich Media Institute'><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/books-150x150.jpg" width="150" height="150" class="attachment-thumbnail" alt="" /></a>
</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/09/24/notes-from-ruby-on-rails-project-night/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The Return of Ruby on Rails Project Night</title>
		<link>http://www.globalnerdy.com/2008/09/17/the-return-of-ruby-on-rails-project-night/</link>
		<comments>http://www.globalnerdy.com/2008/09/17/the-return-of-ruby-on-rails-project-night/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 16:28:39 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Meetups]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Toronto]]></category>

		<category><![CDATA[Rails]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[Ruby/Rails Project Night. Rich Media Institute]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1551</guid>
		<description><![CDATA[
After &#8220;a much-needed summer hiatus&#8221; (which you can read as &#8220;the complete implosion of Toronto&#8217;s worst-run software development shop, which used to host the event&#8221;) Ruby on Rails Project Night makes its comeback this Friday, September 19th at its new home at the Rich Media Institute in Kensington Market.
Event organizer Corina Newby promises that it [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/rails_to_victory.jpg" alt="Rails to Victory" title="Rails to Victory" width="600" height="483"  /></p>
<p>After &#8220;a much-needed summer hiatus&#8221; (which you can read as &#8220;the complete implosion of <a href="http://tsotinc.com/">Toronto&#8217;s worst-run software development shop</a>, which used to host the event&#8221;) <a href="http://correlations.wordpress.com/2008/09/04/sept-19th-ruby-on-rails-project-night-the-rich-media-institute/"><strong>Ruby on Rails Project Night</strong></a> makes its comeback this Friday, September 19th at its new home at the <a href="http://www.richmediainstitute.com/">Rich Media Institute</a> in Kensington Market.</p>
<p>Event organizer <a href="http://correlations.wordpress.com/">Corina Newby</a> promises that it won&#8217;t normally be on Fridays, which should the minds of your significant others, party-going friends or World of Warcraft clans at ease. The event is being held on a Friday this time to accommodate the schedule of special guest <a href="http://www.cincomsmalltalk.com/blog/blogView"><strong>James &#8220;<cite>Smalltalk Tidbits, Industry Rants</cite>&#8221; Robertson</strong></a>, who&#8217;ll be there to give us a presentation of the Smalltalk-based web application framework <a href="http://en.wikipedia.org/wiki/Seaside_(software)">Seaside</a> and the Seaside-based Smalltalk development environment WebVelocity.</p>
<p>Also scheduled is local Ruby on Rails developer <a href="http://pauldoerwald.ca/"><strong>Paul Doerwald</strong></a>, who&#8217;ll be doing a presentation on insights he gained from working with ActiveRecord validation.</p>
<p>As always, one of the greatest benefits of these gatherings is actually meeting local developers who work with or are interested in working with Ruby and Rails. It&#8217;s good for you, your software development career and the future of <a href="http://en.wikipedia.org/wiki/Toronto">Accordion City</a> as a hub for high-tech when gatherings like this take place, so be a part of it!</p>
<p>By the way, did I mention that the event is <strong>FREE</strong>?</p>
<p>Once again, the date is this <strong>Friday, September 19th</strong> at the <a href="http://www.richmediainstitute.com/">Rich Media Institute</a> (<a href="http://maps.google.com/maps?f=q&#038;hl=en&#038;geocode=&#038;q=156+Augusta+Avenue,+Toronto,+ON&#038;sll=37.0625,-95.677068&#038;sspn=46.764446,112.148438&#038;ie=UTF8&#038;z=16&#038;iwloc=addr">156 Augusta Avenue</a>). The presentations will start at 6 p.m. and run until about 7:30. If you&#8217;re planning to attend, let Corina know at <a href="mailto:corecorina@hotmail.com">corecorina@hotmail.com</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/09/17/the-return-of-ruby-on-rails-project-night/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Going Down Memory Lane with C</title>
		<link>http://www.globalnerdy.com/2008/09/16/going-down-memory-lane-with-c/</link>
		<comments>http://www.globalnerdy.com/2008/09/16/going-down-memory-lane-with-c/#comments</comments>
		<pubDate>Tue, 16 Sep 2008 04:00:03 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[What Joey Did]]></category>

		<category><![CDATA[Arduino progamming language]]></category>

		<category><![CDATA[C]]></category>

		<category><![CDATA[my sordid past]]></category>

		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1417</guid>
		<description><![CDATA[The July 25, 1994 issue of Time magazine.
The computer science student phase of my academic career (the less said about the previous phase, in which I was an electrical engineering student, the better) ran from 1991 to a successful conclusion in 1994. 
If you are like me, you strongly connect memories with the music of [...]]]></description>
			<content:encoded><![CDATA[<p class="center"><a href="http://www.time.com/time/magazine/0,9263,7601940725,00.html"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/time_magazine_july_25_1994.jpg" alt="July 25, 1994 issue of Time magazine" title="July 25, 1994 issue of Time magazine" width="300" height="395" /></a><br /><span class="caption">The July 25, 1994 issue of <cite>Time</cite> magazine.</span></p>
<p>The computer science student phase of my academic career (the less said about the previous phase, in which I was an electrical engineering student, the better) ran from 1991 to a successful conclusion in 1994. </p>
<p>If you are like me, you strongly connect memories with the music of the time; you could say that my computer science student phase ran from the time of Nirvana&#8217;s <a href="http://en.wikipedia.org/wiki/Nevermind"><cite>Nevermind</cite></a> and Soundgarden&#8217;s <a href="http://en.wikipedia.org/wiki/Badmotorfinger"><cite>Badmotorfinger</cite></a> to Green Day&#8217;s <a href="http://en.wikipedia.org/wiki/Dookie"><cite>Dookie</cite></a> and The Offspring&#8217;s <a href="http://en.wikipedia.org/wiki/Smash_(album)"><cite>Smash</cite></a>. Let&#8217;s just say that I often showed up to my classes and labs in a flannel shirt.</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/nirvana_nevermind_green_day_dookie.jpg" alt="Album covers: Nirvana&#039;s &quot;Nevermind&quot; and Green Day&#039;s &quot;Dookie&quot;" title="Album covers: Nirvana&#039;s &quot;Nevermind&quot; and Green Day&#039;s &quot;Dookie&quot;" width="500" height="250" /></p>
<p>(If that last paragraph makes you think &#8220;Whoa, that was a long time ago!&#8221;, you&#8217;ll be blown away by the fact that the initial work on C ran from the time of the Beatles&#8217; <a href="http://en.wikipedia.org/wiki/Abbey_Road_(album)"><cite>Abbey Road</cite></a> to Led Zeppelin&#8217;s <a href="http://en.wikipedia.org/wiki/Houses_of_the_Holy"><cite>Houses of the Holy</cite></a>. A fair number of you probably weren&#8217;t even born then.)</p>
<h3>My Student Language of Choice</h3>
<p>I don&#8217;t know what the situation was like at other schools, but at the time, computer science students at <a href="http://queensu.ca/">Crazy Go Nuts University</a> were allowed to hand in programming assignments using the following languages:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Pascal_programming_language">Pascal</a></li>
<li><a href="http://en.wikipedia.org/wiki/Turing_(programming_language)">Turing</a></li>
<li><a href="http://en.wikipedia.org/wiki/C_(programming_language)">C</a></li>
</ul>
<p>(Remember, there was no Java back then. The <a href="http://www.cafeaulait.org/slides/hope/02.html">Green Project</a>, from which the language/platform sprang, was still ongoing at this time, and Java was still going by its <a href="http://ei.cs.vt.edu/book/chap1/java_hist.html">&#8220;Oak&#8221;</a> codename.)</p>
<p>The general recommendation that came from most of my professors was to use Turing. They told us that it was a kinder, gentler language than Pascal and even more so than C, which they implied was designed by dyslexic aliens. When some of us suggested that it might be better to use a language that saw actual use in the real world, many of them countered with the argument that learning principles of computing was more important than learning specific languages. We might&#8217;ve responded by pointing out that <a href="http://research.cs.queensu.ca/~cordy/">one of our professors</a> was a co-creator of Turing and probably got a <a href="http://en.wikipedia.org/wiki/Vigorish">vig</a> for every Turing installation (it was a commercial language), but that might have been an academic career-limiting move.</p>
<p>I ignored their recommendations and went with C. In the lab, I used good ol&#8217; <code>cc</code>. At home, it was <a href="http://en.wikipedia.org/wiki/Turbo_C">Turbo C</a> at first, and later, when I got my first Mac (a <a href="http://www.everymac.com/systems/apple/mac_quadra/stats/mac_quadra_660av.html">Quadra 660AV</a> bought with money from DJing), <a href="http://www.mactech.com/articles/mactech/Vol.07/07.09/ThinkC5.0/">Think C</a>.</p>
<p>I never used C in my professional career. <a href="http://craphound.com/nonfic/mackerel.html">My first job out of school</a> took me away from a world where input and output was all <code>printf()</code> and <code>scanf()</code> to interactive CD-ROMs and Macromedia Director (now <a href="http://www.adobe.com/products/director/">Adobe Director</a> and 7 versions later), and after that, the languages remained pretty high level: Visual Basic, Python, Java, C#, <a href="http://www.nsbasic.com/palm/">NSBasic</a>, PHP and Ruby, with only a slight detour through through Visual C++ and C++Builder.</p>
<h3>My C Books Back Then</h3>
<p class="center"><a href="http://cm.bell-labs.com/cm/cs/cbook/"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/the_c_programming_language.jpg" alt="Cover of &quot;The C Programming Language&quot;" title="Cover of &quot;The C Programming Language&quot;" width="220" height="287" /></a></p>
<p>It&#8217;s almost impossible to talk about C without mentioning &#8220;K&#038;R&#8221;, the nickname for what is considered to be the official bible of C, <a href="http://cm.bell-labs.com/cm/cs/cbook/"><strong><cite>The C Programming Language</cite></strong></a>, which was written by <a href="http://en.wikipedia.org/wiki/Brian_Kernighan">Brian Kernighan</a> and <a href="http://en.wikipedia.org/wiki/Dennis_Ritchie">Dennis Ritchie</a>. The latest edition of the book &#8212; the second edition &#8212; is a bit long in the tooth as it was written in 1988, but for the most part, everything in this book should still apply to the current <a href="http://en.wikipedia.org/wiki/C99">C99</a> standard.</p>
<p>I never owned a copy of the book in my student days. I signed it out when necessary from the electrical engineering/computer science library in <a href="http://www.queensu.ca/secretariat/History/bldgs/walt.html">Walter Light Hall</a>. I <em>did</em> own a copy for a brief period in 2002 when my <a href="http://www.joeydevilla.com/2007/11/14/forgiving-the-deadbeat-ex-housemates-debt/">deadbeat ex-housemate</a> left a lot of his stuff behind, but I sold it (along with most of his stuff) in order to recoup some of the money lost from his stiffing me on rent, utilities, groceries and the largest domestic phone bill I&#8217;ve ever grappled with.</p>
<p class="center"><a href="http://www.cs.ucsc.edu/~pohl/abc4.html"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/a_book_on_c.jpg" alt="Cover of &quot;A Book on C&quot;" title="Cover of &quot;A Book on C&quot;" width="220" height="318" /></a></p>
<p>The books I had while at Crazy Go Nuts University were the second edition of <a href="http://www.cs.ucsc.edu/~pohl/abc4.html"><strong><cite>A Book on C</cite></strong></a> and <cite>Understanding C Pointers</cite> (a book that seems to be no longer in print). I liked <cite>A Book on C</cite> enough to pick up the fourth edition on sale a couple of years ago, and someone out there has forgotten to give me back my copy of <cite>Understanding C Pointers</cite> (you know who you are!).</p>
<h3>Back to C</h3>
<p>I&#8217;ve decided to get back into C for a number of reasons.</p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/internet_tough_guy_magazine.jpg" alt="&quot;Internet Tough Guy&quot; Magazine" title="&quot;Internet Tough Guy&quot; Magazine" width="300" height="440" /></p>
<p>I have to admit that one of those reasons is completely irrational: it&#8217;s ego. There&#8217;s certain geek cred that comes with having at least some proficiency in C. While I had those bragging rights back in school, I can&#8217;t honestly claim them now; I haven&#8217;t even written a file whose name ends in <code>.c</code> in over a decade. Luckily, I had a pretty good grasp of C back in school, and the noodling I&#8217;ve been doing with good old <code>gcc</code> suggests that I&#8217;ve still got it, which is pretty reassuring. </p>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/iphone_arduino_mac_guy.jpg" alt="iPhone, Arduino 480 and the &quot;Mac Guy&quot;" title="iPhone, Arduino 480 and the &quot;Mac Guy&quot;" width="487" height="273" /></p>
<p>I&#8217;ve also been meaning to do some development with things that are programmed in C or C dialects:</p>
<ul>
<li>The <a href="http://arduino.cc/"><strong>Arduino</strong></a> electronics prototyping platform has its own programming language based on C. I&#8217;ve been meaning to try out hardware hacking with the folks at the local group <a href="http://hackerspaces.org/wiki/HackLabTO">HacklabTO</a>.</li>
<li>I&#8217;ve also been thinking about putting together some <strong>Mac OS X</strong> and <strong>iPhone</strong> apps, which require <a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a>.</li>
<li>I&#8217;ve even been thinking about doing some <strong>GTK</strong> noodling, which is done in good ol&#8217; C.</li>
</ul>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/09/homer_simpson_brain.jpg" alt="Homer Simpson&#039;s brain x-ray" title="Homer Simpson&#039;s brain x-ray" width="410" height="307" /></p>
<p>Finally, there&#8217;s the matter of just making myself a better programmer by working in C by refreshing my knowledge of the low-level stuff that C requires you to work with, and also the &#8220;brain stretch&#8221; that comes with working with a language and environment (what with going back to strong typing, compiling and <strong>make</strong>) that I haven&#8217;t worked in for some time.</p>
<p>I&#8217;ll be doing some C coding in my spare time, as well as noodling with the Arduino programming languane and Objective-C, and I&#8217;ll be posting my notes, observations and experiences here. As I&#8217;m fond of saying on this blog, watch this space!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/09/16/going-down-memory-lane-with-c/feed/</wfw:commentRss>
		</item>
		<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</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 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="800" height="600" /></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="800" height="600" /></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="800" height="600" /></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="800" height="600" /></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="800" height="600" /></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="800" height="600" /></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="800" height="600" /></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="800" height="600" /></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>
		</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</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 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>
		</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</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 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>
		</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</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 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>
		</item>
		<item>
		<title>Code Swarm: A Visual History of Python Commits</title>
		<link>http://www.globalnerdy.com/2008/08/07/code-swarm-a-visual-history-of-python-commits/</link>
		<comments>http://www.globalnerdy.com/2008/08/07/code-swarm-a-visual-history-of-python-commits/#comments</comments>
		<pubDate>Thu, 07 Aug 2008 21:05:19 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[history]]></category>

		<category><![CDATA[Python]]></category>

		<category><![CDATA[timelines]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1176</guid>
		<description><![CDATA[The Code_Swarm video is an interesting visualization of the evolution of the work done on the Python programming language and the people involved, tracing its evolution from late 1990 to mid-2005.
code_swarm - Python from Michael Ogawa on Vimeo.
The intro for the video says:

In 1991, Guido van Rossum released his Python scripting language to the public.
This [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.vimeo.com/1093745?pg=embed&#038;sec=1093745"><strong><cite>Code_Swarm</cite></strong></a> video is an interesting visualization of the evolution of the work done on the Python programming language and the people involved, tracing its evolution from late 1990 to mid-2005.</p>
<p class="center"><object width="400" height="302"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id=1093745&amp;server=www.vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://www.vimeo.com/moogaloop.swf?clip_id=1093745&amp;server=www.vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="302"></embed></object><br /><span class="caption"><a href="http://www.vimeo.com/1093745?pg=embed&amp;sec=1093745"><strong>code_swarm - Python</strong></a> from <a href="http://www.vimeo.com/michaelogawa?pg=embed&amp;sec=1093745">Michael Ogawa</a> on <a href="http://vimeo.com?pg=embed&amp;sec=1093745">Vimeo</a>.</span></p>
<p>The intro for the video says:</p>
<blockquote><p>
In 1991, Guido van Rossum released his Python scripting language to the public.</p>
<p>This video will take you through the history of the project, compressed into a fraction of the time.</p>
<p>You will see the names of developers fade in and out of prominence, while the files they work on swirl around them.</p>
<p>Red files are core code. Blue files are documents. Yellow files are modules. The histogram on the bottom tracks the size and time of commits. When a person makes a commit, their name stands out. The files they commit also stand out. Files grow in size every time they are committed. Files and people gradually fade when there is no activity.
</p></blockquote>
<p>[<a href="http://waronfolly.tumblr.com/post/44599365/code-swarm-a-visual-history-of-python-via-foca">Thanks to <cite>The War on Folly</cite>.</a>]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/07/code-swarm-a-visual-history-of-python-commits/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Enumerating Enumerable: Enumerable#find_all / Enumerable#select</title>
		<link>http://www.globalnerdy.com/2008/08/07/enumerating-enumerable-enumerablefind_all-enumerableselect/</link>
		<comments>http://www.globalnerdy.com/2008/08/07/enumerating-enumerable-enumerablefind_all-enumerableselect/#comments</comments>
		<pubDate>Thu, 07 Aug 2008 19:04:49 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1155</guid>
		<description><![CDATA[
We&#8217;re at lucky number 13 &#8212; the thirteenth article in the Enumerating Enumerable series, which covers the methods of Ruby&#8217;s Enumerable module. I started this series after being disappointed with the documentation at Ruby-Doc.org.
In this article, I&#8217;m covering the find_all &#8212; a.k.a. select &#8212; method.
In case you missed any of the previous articles, they&#8217;re listed [...]]]></description>
			<content:encoded><![CDATA[<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>We&#8217;re at lucky number 13 &#8212; the thirteenth article in the <strong><cite>Enumerating Enumerable</cite></strong> series, which covers the methods of Ruby&#8217;s <code>Enumerable</code> module. I started this series after being disappointed with the documentation at Ruby-Doc.org.</p>
<p>In this article, I&#8217;m covering the <code>find_all</code> &#8212; a.k.a. <code>select</code> &#8212; 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>
</ol>
<h3>Enumerable#find_all / Enumerable#select Quick Summary</h3>
<p class="center"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/ruby_enumerablefind_all_enumerableselect.jpg" alt="Graphic representation of the \&quot;find_all\&quot; / \&quot;select\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" title="Graphic representation of the \&quot;find_all\&quot; / \&quot;select\&quot; method in Ruby\&#039;s \&quot;Enumerable\&quot; module" width="317" height="304" /></p>
<table>
<tr>
<th>In the simplest possible terms</th>
<td>Which 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.</td>
</tr>
<tr>
<th>Returns</th>
<td>An array containing the items in the collection that meet the given criteria. If no items in the collection meet the given criteria, this is an empty array.</td>
</tr>
<tr>
<th>RubyDoc.org&#8217;s entry</th>
<td><a href="http://www.ruby-doc.org/core-1.9/classes/Enumerable.html#M002966">Enumerable#find_all / Enumerable#select</a></td>
</tr>
</table>
<h3>Enumerable#find_all / Enumerable#select and Arrays</h3>
<p>When used on an array, <code>find_all</code> and its synonym <code>select</code> passes each item from the array to the block, returning an array containing only those elements in the original array for which the block returns a value that doesn&#8217;t evaluate to <code>false</code>.</p>
<p>If no item in the array causes the block to return a value that doesn’t evaluate to false, <code>find_all</code>/<code>select</code> returns an empty array.</p>
<p>In the examples that follow (which are based on <a href="http://www.globalnerdy.com/2008/07/07/enumerating-enumerable-enumerabledetectenumerablefind/">my examples for the <code>detect</code>/<code>find</code> method</a>), I’ll be using the <code>find_all</code> method. <code>select</code> does exactly the same thing; it’s just that I prefer <code>find_all</code>.</p>
<p><code>
<pre>
# Once again,  I shall 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 ones have
# a name longer than 8 characters?
classic_rock_bands.find_all {|band| band.length > 8}
=> ["Black Sabbath", "Ted Nugent and the Amboy Dukes", "Scorpions", "Van Halen"]

# Which ones have a name exactly 5 characters long?
classic_rock_bands.find_all {|band| band.length == 5}
=> ["AC/DC", "Queen"]

# If no band in the array meets the criteria,
# find_all returns an empty array.
# Which ones have names shorter than 5 characters?
classic_rock_bands.find_all {|band| band.length < 5}
=> []
</pre>
<p></code></p>
<h3>Enumerable#find_all / Enumerable#select and Hashes</h3>
<p>When used on a hash, <code>find_all</code>/<code>select</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_all</code>/<code>select</code> passes each item from the hash to the block, returning an array containing only those items in the original array for which the block returns a value that doesn&#8217;t evaluate to <code>false</code>.</p>
<p>Note that each item in the result array is a two-element array corresponding to an item from the original hash. In this array, element 0 contains the key and element 1 contains the corresponding value.</p>
<p>If no item in the hash causes the block to return a value that doesn’t evaluate to false, find_all/select returns an empty array.</p>
<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}
=> {"AC/DC"=>1973, "Black Sabbath"=>1968, "Queen"=>1970,
"Ted Nugent and the Amboy Dukes"=>1967, "Scorpions"=>1965, "Van Halen"=>1972}

# Ruby 1.9 preserves hash order so that hashes keep the order in which
# you defined them, while Ruby 1.8 puts them in some mysterious order.
# All these examples are in Ruby 1.9

# Which bands were founded in 1970 or later?
years_founded.find_all {|band| band[1] >= 1970}
=> [["AC/DC", 1973], ["Queen", 1970], ["Van Halen", 1972]]

# Here's another way of phrasing it:
years_founded.find_all {|band, year_founded| year_founded >= 1970}
=> [["AC/DC", 1973], ["Queen", 1970], ["Van Halen", 1972]]

# Which bands were founded after 1980?
years_founded.find_all {|band, year_founded| year_founded > 1980}
=> []
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/07/enumerating-enumerable-enumerablefind_all-enumerableselect/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Build Status Interfaces</title>
		<link>http://www.globalnerdy.com/2008/08/01/build-status-interfaces/</link>
		<comments>http://www.globalnerdy.com/2008/08/01/build-status-interfaces/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 16:30:09 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[cute]]></category>

		<category><![CDATA[user interfaces]]></category>

		<guid isPermaLink="false">http://www.globalnerdy.com/?p=1125</guid>
		<description><![CDATA[Having a continuous integration system is nice, but what&#8217;s even nicer is if that system has a really clear way of telling you whether the build is working. Last.fm weren&#8217;t happy with build status messages on the command line and went the extra mile to set up these illuminated bears:

Last.fm&#8217;s Adrian Woodhead writes:

These 3 bears [...]]]></description>
			<content:encoded><![CDATA[<p>Having a continuous integration system is nice, but what&#8217;s even nicer is if that system has a really clear way of telling you whether the build is working. <a href="http://blog.last.fm/2008/08/01/quality-control"><strong>Last.fm weren&#8217;t happy with build status messages on the command line and went the extra mile to set up these illuminated bears:</strong></a></p>
<p class="center"><a href="http://blog.last.fm/2008/08/01/quality-control"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/lastfm_build_bears.jpg" alt="Last.fm\&#039;s red, yellow and green \&quot;build bears\&quot;" title="Last.fm\&#039;s red, yellow and green \&quot;build bears\&quot;" width="370" height="391" /></a></p>
<p>Last.fm&#8217;s Adrian Woodhead <a href="http://blog.last.fm/2008/08/01/quality-control">writes</a>:</p>
<blockquote><p>
These 3 bears sit in a prominent position and watch our developer’s every move. When things are good we have a green bear gently glowing and purring, when changes are being processed a yellow bear joins the party, and if the build gets broken the growling evil red bear makes an appearance. The developer who broke things usually goes a similar shade of red while frantically trying to fix whatever was broken while the others chortle in the background.
</p></blockquote>
<p>I&#8217;ve been meaning to get back into a little hardware hacking (something I haven&#8217;t done since I was a teen) and learn how to build computer-driven gizmos like Last.fm&#8217;s bears. In the meantime, I&#8217;ll have to satisfy myself by <a href="http://www.seanbonner.com/blog/archives/002270.php">page-slapping</a> the development team at <a href="http://b5media.com/">b5</a> with these images created by <a href="http://blog.bigswingingdeveloper.com/">Big Swinging Developer</a>&#8230;</p>
<h3>You Broke the Build!</h3>
<p class="center"><a href="http://www.youbrokethebuild.com/"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/you_broke_the_build.jpg" alt="\&quot;You broke the build!\&quot; graphic" title="\&quot;You broke the build!\&quot; graphic" width="451" height="600" /></a></p>
<h3>&#8220;Builds on My Machine&#8230;&#8221;</h3>
<p class="center"><a href="http://www.buildsonmymachine.com/"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/builds_on_my_machine.jpg" alt="\&quot;Builds on my machine\&quot; graphic" title="\&quot;Builds on my machine\&quot; graphic" width="592" height="600" /></a></p>
<h3>Where&#8217;s the Build?</h3>
<p class="center"><a href="http://www.wheresthebuild.com/"><img src="http://www.globalnerdy.com/wordpress/wp-content/uploads/2008/08/wheres_the_build.jpg" alt="\&quot;Where\&#039;s the build?\&quot; graphic" title="\&quot;Where\&#039;s the build?\&quot; graphic" width="458" height="600" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/08/01/build-status-interfaces/feed/</wfw:commentRss>
		</item>
		<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</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 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>
		</item>
		<item>
		<title>Take Hampton&#8217;s Ruby Survey!</title>
		<link>http://www.globalnerdy.com/2008/07/29/take-hamptons-ruby-survey/</link>
		<comments>http://www.globalnerdy.com/2008/07/29/take-hamptons-ruby-survey/#comments</comments>
		<pubDate>Tue, 29 Jul 2008 20:26:35 +0000</pubDate>
		<dc:creator>joey</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[survey]]></category>

		<guid isPermaLink="false">http://globalnerdy.com/?p=1964</guid>
		<description><![CDATA[Photo by rcoder.Click the photo to see the original on its Flickr page.
Hampton &#8220;HAML&#8221; Catlin of Unspace (you know, the development shop that put RubyFringe together) has created a survey that he&#8217;d like as many people who code in Ruby to take. It&#8217;s quick and painless, and he&#8217;ll share the data once he&#8217;s compiled it.
]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://flickr.com/photos/rcoder/2681785906/"><img src="http://globalnerdy.com/wordpress/wp-content/uploads/2008/07/take_hamptons_ruby_survey1.jpg" alt="\&quot;Take Hampton\&#039;s Ruby Survey\&quot;: Hampton Catlin pointing at his survey, projected on a screen" title="\&quot;Take Hampton\&#039;s Ruby Survey\&quot;: Hampton Catlin pointing at his survey, projected on a screen" width="500" height="499" /></a><br /><span class="caption">Photo by rcoder.<br />Click the photo to see the original on its Flickr page.</span></p>
<p>Hampton &#8220;HAML&#8221; Catlin of <a href="http://unspace.ca/">Unspace</a> (you know, the development shop that put <a href="http://rubyfringe.com/">RubyFringe</a> together) has created <a href="http://survey.hamptoncatlin.com/"><strong>a survey that he&#8217;d like as many people who code in Ruby to take</strong></a>. It&#8217;s quick and painless, and he&#8217;ll share the data once he&#8217;s compiled it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/29/take-hamptons-ruby-survey/feed/</wfw:commentRss>
		</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</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 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>
		</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</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 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_ensig