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

<channel>
	<title>Global Nerdy &#187; cycle</title>
	<atom:link href="http://www.globalnerdy.com/tag/cycle/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.globalnerdy.com</link>
	<description>Tech Evangelist Joey deVilla on software development, tech news and other nerdy stuff</description>
	<lastBuildDate>Thu, 19 Nov 2009 02:16:42 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Enumerating Enumerable: Enumerable#cycle</title>
		<link>http://www.globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/</link>
		<comments>http://www.globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/#comments</comments>
		<pubDate>Sun, 06 Jul 2008 04:00:22 +0000</pubDate>
		<dc:creator>Joey deVilla</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[Ruby]]></category>

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

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

<ol>
    <li><a href="http://globalnerdy.com/2008/06/23/enumerating-enumerable-enumerableall/">all?</a></li>
    <li><a href="http://globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/">any?</a></li>
    <li><a href="http://globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/">collect / map</a></li>
    <li><a href="http://globalnerdy.com/2008/07/02/enumerating-enumerable-enumerablecount/">count</a></li>
    </ol>

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

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

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

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

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

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

days.next
=> "Tuesday"

days.next
=> "Wednesday"

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

days.next
=> "Monday"

...

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

days.next
=> "Sunday"

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

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

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

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

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

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

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

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

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

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

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

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

...

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

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

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

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

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

# Let's assign dinner-cooking duties to the crew!
10.times do
    day = days.next
    dinner = dinners.next
    chef = crewmembers.next[1]
    puts "On #{day}, Crewman #{chef} will prepare #{dinner}."
end
=> On Monday, Crewman Picard will prepare Jerk chicken.
On Tuesday, Crewman Riker will prepare Lamb vindaloo.
On Wednesday, Crewman Data will prepare Chicken fried steak.
On Thursday, Crewman Worf will prepare Yeung Chow fried rice.
On Friday, Crewman Picard will prepare Tonkatsu.
On Saturday, Crewman Riker will prepare Coq au Vin.
On Sunday, Crewman Data will prepare Chunky bacon.
On Monday, Crewman Worf will prepare Pierogies.
On Tuesday, Crewman Picard will prepare Salisbury steak.
On Wednesday, Crewman Riker will prepare Bibim Bap.
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.globalnerdy.com/2008/07/06/enumerating-enumerable-enumerablecycle/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
