Categories
Uncategorized

Enumerating Enumerable: Enumerable#each_with_index

Enumerating Enumerable

Here’s number 11 in the Enumerating Enumerable series, in which I’m trying to outdo RubyDoc.org in their documentation of Ruby’s key Enumerable module. In this article, I cover the each_with_index method.

In case you missed the earlier articles, they’re listed and linked below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle
  6. detect / find
  7. drop
  8. drop_while
  9. each_cons
  10. each_slice

Enumerable#each_with_index Quick Summary

Graphic representation of the \"each_with_index\" method in Ruby\'s \"Enumerable\" module

In the simplest possible terms Think of each_with_index as a version of each that includes an extra piece of information: a number representing the current iteration’s element’s position in the collection.
Ruby version 1.8 and 1.9
Expects An optional block to receive the values from each iteration.
Returns
  • The original collection, if used with a block.
  • An Enumerator object that outputs the collection’s items and indexes, if used without a block.
RubyDoc.org’s entry Enumerable#each_with_index

Enumerable#each_with_index and Arrays

When used with on an array and given a block, each_with_index 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’ll use the “Justice League” example:

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

Note that unlike the each_cons and each_slice, each_with_index doesn’t return nil, but the original array, just like each does. each_cons and each_slice are newer methods that were introduced in Ruby 1.9; perhaps Matz and company decided that it made more sense for “each” methods to return nil from now on. each and each_with_index 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!

Enumerable#each_with_index and Hashes

When used with on a hash and given a block, each_with_index 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’ll use the “Enterprise Crew” example:

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

Enumerable#each_with_index Oddities

Blocks with a Single Parameter

What happens if you use each_with_index with a block that has only one parameter? You’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’s not the case:

# 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"]

When each_with_index 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, each_with_index behaves just like each.

Without a Block

What happens if you use each_with_index without a block to create an Enumerator object that spits out the next item when its next method is called? This:

hero = justice_league.each_with_index
=> #<Enumerable::Enumerator:0x159cb98>

hero.next
=> "Aquaman"

hero.next
=> "Batman"

hero.next
=> "Black Canary"

Note that calling next only yields the next item in the collection; the index information is lost. In this case, each_with_index behaves just like each.

Categories
Uncategorized

Enumerating Enumerable: Enumerable#each_slice

Enumerating Enumerable

Ten installments already? That’s right, this is the tenth Enumerating Enumerable 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 Enumerable module than Ruby-Doc.org does, with pretty pictures and more in-depth examples!

In this article, I’m going to cover each_slice, which got introduced in Ruby 1.9.

If you missed any of the earlier articles, I’ve listed them all below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle
  6. detect / find
  7. drop
  8. drop_while
  9. each_cons

Enumerable#each_slice Quick Summary

Graphic representation of the "each_slice" method in Ruby's "Enumerable" module

In the simplest possible terms Given a number n, split the array into n-element slices (if the number of elements in the array isn’t evenly divisible by n, just put the remaining elements in the last slice), then iterate through those slices.
Ruby version 1.9 only
Expects
  • A number n describing the size of the iteration slice.
  • An optional block to receive the values from each iteration.
Returns
  • nil, if used with a block.
  • An Enumerator object that outputs n-sized slices of the collection, if used without a block.
RubyDoc.org’s entry Enumerable#each_slice

Enumerable#each_slice and Arrays

When used on an array with a block, each_slice takes a numeric argument n and splits the array into slices of length n (if the number of elements in the array isn’t evenly divisible by n, the remaining elements are put into the last slice). each_slice then iterates through the set of slices, passing each slice to the block. After the final iteration, each_slice returns nil.

Since this is yet another case when an showing an example makes things very clear, I’ll do just that, using the same example data I used in the article on each_cons:

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

When used on an array without a block, each_slice takes a numeric argument n and returns an Enumerator that outputs slices of the array when its next method is called. Here’s an example:

teams_of_3 = justice_league.each_slice(3)
=> #<Enumerable::Enumerator:0x007fc73baa9830>

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
=> #<Enumerable::Enumerator:0x007fc73baa9830>

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

Enumerable#each_slice and Hashes

When used on an hash with a block, each_slice takes a numeric argument n and splits the hash into arrays of length n (if the number of elements in the array isn’t evenly divisible by n, 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.

each_slice then iterates through the set of arrays, passing each array to the block. After the final iteration, each_slice returns nil.

Here’s an example, using the same example data I used in the article on each_cons:

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

When used on a hash without a block, each_slice takes a numeric argument n and returns an Enumerator that outputs arrays when its next method is called. Here’s an example:

away_teams_of_3 = enterprise_crew.each_slice(3)
=> #<Enumerable::Enumerator:0x007fc73ba44c50>

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
=> #

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

Categories
Uncategorized

Enumerating Enumerable: Enumerable#each_cons

Enumerating Enumerable

Welcome to the ninth installment of Enumerating Enumerable, the series of articles where I attempt to do a better job at documenting Ruby’s Enumerable module than Ruby-Doc.org does.

I’m going through the Enumerable‘s methods in alphabetical order, and we’ve reached the methods that are variations on each In this article, I’m going to cover each_cons, which got introduced in Ruby 1.9.

If you missed any of the earlier articles, I’ve listed them all below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle
  6. detect / find
  7. drop
  8. drop_while

Enumerable#each_cons Quick Summary

Graphic representation of the \"each_cons\" method in Ruby\'s \"Enumerable\" module

In the simplest possible terms Think of each_cons as an each that takes a number n and spits out n elements at a time.
Ruby version 1.9 only
Expects A number n describing the number of elements to be fed to the block.
Returns
  • nil if used with a block
  • An Enumerator object that outputs n-sized consecutive array slices of the collection if used without a block.
RubyDoc.org’s entry Enumerable#each+cons

Enumerable#each_cons and Arrays

When used on an array and given a block and a number n as an argument, each_cons is like an each that goes through each element in the array and outputs an n-sized array slice of the original array starting at the current element.

each_cons is one of those methods that’s really tough to describe. This is one of those cases where a demonstrating trumps describing…

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

Note that in this case, each_cons returns nil.

each_cons can also be used without providing a block. In this case, you’re using it to create an Enumerator object that you can then use to spit out array slices when you call its next method:

# Let's create an enumerator that we can use to give us three-person
# superhero teams
teams_of_3 = justice_league.each_cons(3)
=> #

# 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
=> #

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

Enumerable#each_cons and Hashes

When used on a hash and given a block and a number n as an argument, each_cons is like an each that goes through each element in the array and outputs an n-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.

Again, examples speak louder than descriptions:

enterprise_crew = {:captain => "Picard",
                   :first_officer => "Riker",
                   :science_officer => "Data",
                   :tactical_officer => "Worf",
                   :chief_engineer => "LaForge",
                   :chief_medical_officer => "Crusher",
                   :ships_counselor => "Troi",
                   :annoying_ensign => "Crusher",
                   :attractive_ensign => "Ro",
                   :expendable_crew_member => "Smith"}
=> {:captain=>"Picard", :first_officer=>"Riker", :science_officer=>"Data", :tact
ical_officer=>"Worf", :chief_engineer=>"LaForge", :chief_medical_officer=>"Crush
er", :ships_counselor=>"Troi", :annoying_ensign=>"Crusher", :attractive_ensign=>
"Ro", :expendable_crew_member=>"Smith"}

enterprise_crew.each_cons(3) {|team| p team}
=> [[:captain, "Picard"], [:first_officer, "Riker"], [:science_officer, "Data"]]
[[:first_officer, "Riker"], [:science_officer, "Data"], [:tactical_officer, "Worf"]]
[[:science_officer, "Data"], [:tactical_officer, "Worf"], [:chief_engineer, "LaForge"]]
[[:tactical_officer, "Worf"], [:chief_engineer, "LaForge"], [:chief_medical_officer, "Crusher"]]
[[:chief_engineer, "LaForge"], [:chief_medical_officer, "Crusher"], [:ships_counselor, "Troi"]]
[[:chief_medical_officer, "Crusher"], [:ships_counselor, "Troi"], [:annoying_ensign, "Crusher"]]
[[:ships_counselor, "Troi"], [:annoying_ensign, "Crusher"], [:attractive_ensign, "Ro"]]
[[:annoying_ensign, "Crusher"], [:attractive_ensign, "Ro"], [:expendable_crew_member, "Smith"]]
=> nil

As with arrays, each_cons, when used on a hash, returns nil.

Again, as with arrays, each_cons can also be used without providing a block to create an Enumerator:

# Starfleet has decided to let the ship's computer determine
# the away teams, which are groups of 3
away_teams_of_3 = enterprise_crew.each_cons(3)
=> #

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

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

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

# Let's go back to the first away team
away_teams_of_3.rewind
=> #

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

Categories
Uncategorized

Enumerating Enumerable: Enumerable#drop_while

After the wackiness of the past couple of weeks — some travel to see family, followed by a busy week of tech events including DemoCamp 18, Damian Conway’s presentation, FAILCamp and RubyFringe — I’m happy to return to Enumerating Enumerable, the article series in which I attempt to do a better job at documenting Ruby’s Enumerable module than Ruby-Doc.org does.

In this article, the eighth in the series, I’m going to cover a method introduced in Ruby 1.9: drop_while.

I’m going through the Enumerable‘s methods in alphabetical order. If you missed any of the earlier articles, I’ve listed them all below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle
  6. detect / find
  7. drop

Enumerable#drop_while Quick Summary

Graphic representation of the \"drop_while\" method in Ruby\'s \"Enumerable\" module

In the simplest possible terms Given a collection and a condition, return an array made of the collection’s items, starting the first item that doesn’t meet the condition.
Ruby version 1.9 only
Expects A block containing the condition.
Returns An array made up of the remaining items, if there are any.
RubyDoc.org’s entry Enumerable#drop_while

Enumerable#drop_while and Arrays

When used on an array, drop_while returns a copy of the array created by going through the original array’s items in order, dropping elements until it encounters the an element that does not meet the condition. The resulting array is basically a copy of the original array, starting at the first element that doesn’t meet the condition in the block.

As in many cases, things become clearer with some examples:

# In Canada, and in fact in all but 2 countries in the world,
# the weather report gives temperatures in Celsius!
temperatures = [28, 25, 30, 22, 27]
=> [28, 25, 30, 22, 27]

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

# The block returns false for the first element,
# so drop_while returns an array like the original,
# starting at the first element
# (in other words, a copy of the original).
temperatures.drop_while {|temperature| temperature < 28}
=> [28, 25, 30, 22, 27]

Enumerable#drop_while and Hashes

When used on a hash, drop_while effectively:

  • Creates an array based on the hash, with each element in the hash represented as a two-element array where the first element contains the key and the second element containing the corresponding value, then
  • goes through each element in the array, dropping elements until it encounters the first element that doesn’t meet the condition in the block. The resulting array is an array of two-element arrays, starting at the first element that doesn’t meet the condition in the block.

Once again, examples will make this all clear:

# We're basically taking the array from the previous example
# and dressing it up in a hash
city_temperatures = {"New York" => 28, \
                     "Toronto" => 25, \
                     "Washington" => 30, \
                     "Montreal" => 22, \
                     "Boston" => 27}
=> {"New York"=>28, "Toronto"=>25, "Washington"=>30,
"Montreal"=>22, "Boston"=>27}

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

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

# The block returns false for the first element,
# so drop_while returns an array based on the hash,
# starting at the first element
# (in other words, an array based on the original hash,
# with key-value pairs turned into two-element arrays).
city_temperatures.drop_while {|city,temperature| temperature < 28}
=> [["New York", 28], ["Toronto", 25], ["Washington", 30],
["Montreal", 22], ["Boston", 27]]

Enumerable#drop_while’s Evil Twin, Enumerable#take_while

I’ll cover take_while in detail in a later installment, but for now, an example should suffice:

city_temperatures.drop_while {|city_temperature| city_temperature[1] < 30}
=> [["Washington", 30], ["Montreal", 22], ["Boston", 27]]

city_temperatures.take_while {|city_temperature| city_temperature[1] < 30}
=> [["New York", 28], ["Toronto", 25]]

Categories
Uncategorized

Enumerating Enumerable: Enumerable#drop

Enumerating Enumerable marches on!

This is the seventh article in my series in which I try to do a better job of documenting Ruby’s Enumerable module than Ruby-Doc.org does. If you’ve missed the other articles in the series, they’re listed below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle
  6. detect / find

In this installment, I cover a method added in Ruby 1.9: drop.

Enumerable#drop Quick Summary

Graphic representation of the \"drop\" method in Ruby\'s \"Enumerable\" module

In the simplest possible terms Given a collection and a number n, create an array made of the items of the collection with the first n items removed.
Ruby version 1.9 only
Expects The number of elements to remove from the start of the collection.
Returns An array made up of the remaining items, if there are any./td>
RubyDoc.org’s entry Enumerable#drop

Enumerable#drop and Arrays

With an array, drop takes a number n as an argument and returns an array created by removing the first n elements of the array. The resulting array is made up of the remaining elements.

# These are the favourite bands of RubyFringe organizer
# Meghan Katleen Millard's, according to her Facebook profile
meghans_fave_bands = ["Afghan Whigs", "Bjork", "Charles Mingus",
"Deerhunter", "Electrelane", "Francois Hardy", "Godspeed You Black Emperor!"]
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter", "Electrelane",
"Francois Hardy", "Godspeed You Black Emperor!"]

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

# The original array is not affected
meghans_fave_bands
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter", "Electrelane",
"Francois Hardy", "Godspeed You Black Emperor!"]

Enumerable#drop and Hashes

With an hash, drop takes a number n as an argument and returns an array created by removing the first n elements of the array (drop is only in Ruby 1.9 and later, where hashes keep the order in which they were defined, so its results are predictable). The resulting array is made up of the remaining elements, with each element converted into a two-element array where element 0 is the key and element 1 is the corresponding value.

# Here's a hash of the first five U.S. states
# (in terms of alphabetical order) and their capitals.
# This example is in Ruby 1.9, which means that
# the hash keys will stay in the order in which
# they were defined.
states_and_capitals = {"Alabama" => "Montgomery", \
                       "Alaska"  => "Juneau", \
                       "Arizona" => "Phoenix", \
                       "Arkansas" => "Little Rock", \
                       "California" => "Sacramento"}
=> {"Alabama"=>"Montgomery", "Alaska"=>"Juneau", "Arizona"=>"Phoenix",
"Arkansas"=>"Little Rock", "California"=>"Sacramento"}

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

# The original hash is not affected
states_and_capitals
=> {"Alabama"=>"Montgomery", "Alaska"=>"Juneau", "Arizona"=>"Phoenix",
"Arkansas"=>"Little Rock", "California"=>"Sacramento"}

Enumerable#take: Enumerable#drop’s Evil Twin

I’ll cover take in detail in a later installment, but for now, an example should suffice:

meghans_fave_bands = ["Afghan Whigs", "Bjork", "Charles Mingus",
"Deerhunter", "Electrelane", "Francois Hardy", "Godspeed You Black Emperor!"]
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter", "Electrelane",
"Francois Hardy", "Godspeed You Black Emperor!"]

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

meghans_fave_bands.take(4)
=> ["Afghan Whigs", "Bjork", "Charles Mingus", "Deerhunter"]

Categories
Uncategorized

Enumerating Enumerable: Enumerable#detect/Enumerable#find

Here’s another article in the Enumerating Enumerable series, in which I attempt to improve upon RubyDoc.org’s documentation for the Enumerable module, which I find rather lacking. If you’ve missed the previous articles in the series, I’ve listed them below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle

This installment covers a method that goes by two names: detect or find. I personally prefer find, as it’s shorter and the term I tend to use for its function.

Enumerable#detect/Enumerable#find Quick Summary

Graphic representation of the \"detect\" or \"find\" method in Ruby\'s \"Enumerable\" module.

In the simplest possible terms What’s the first item in the collection that meets the given criteria?
Ruby version 1.8 and 1.9
Expects
  • A block containing the criteria.
  • An optional argument containing a proc that calculates a “default” value — that is, the value to return if no item in the collection matches the criteria.
Returns The first item in the collection that matches the criteria, if one exists.
If no such item exists in the collection, detect/find returns:

  • nil is returned if no argument is provided
  • the value of the argument, if one is provided.
RubyDoc.org’s entry Enumerable#detect / Enumerable#find

Enumerable#detect/Enumerable#find and Arrays

When used on an array without an argument, detect/find passes each item from the collection to the block and…

  • If the current item causes the block to return a value that doesn’t evaluate to false, detect/find stops going through collection and returns the item.
  • If no item in the collection causes the block to return a value that doesn’t evaluate to false, detect/find returns nil.

In the examples that follow, I’ll be using the find method. detect does exactly the same thing; it’s just that I prefer find.

# Time to establish my "old fart" credentials
classic_rock_bands = ["AC/DC", "Black Sabbath", "Queen", \
"Ted Nugent and the Amboy Dukes", "Scorpions", "Van Halen"]
=> ["AC/DC", "Black Sabbath", "Queen", "Ted Nugent and the Amboy Dukes",
"Scorpions", "Van Halen"]

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

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

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

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

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

# If no band in the array meets the criteria,
# "find" returns nil.
# There are no bands in the list with names shorter
# than 5 characters...
classic_rock_bands.find {|band| band.length < 5}
=> nil

Using the optional argument is a topic big enough to merit its own section, which appears later in this article.

Enumerable#detect/Enumerable#find and Hashes

When used on a hash and a block is provided, detect/find passes each key/value pair in the hash to the block, which you can “catch” as either:

  1. A two-element array, with the key as element 0 and its corresponding value as element 1, or
  2. Two separate items, with the key as the first item and its corresponding value as the second item.

When used on a hash without an argument, detect/find passes each item from the collection to the block and…

  • If the current item causes the block to return a value that doesn’t evaluate to false, detect/find stops going through collection and returns the item.
  • If no item in the collection causes the block to return a value that doesn’t evaluate to false, detect/find returns nil.

years_founded = {"AC/DC" => 1973, \
                 "Black Sabbath" => 1968, \
                 "Queen" => 1970, \
                 "Ted Nugent and the Amboy Dukes" => 1967, \
                 "Scorpions" => 1965, \
                 "Van Halen" => 1972}
# Ruby 1.8 re-orders hashes in some mysterious way that is almost never
# the way you entered it. Here's what I got in Ruby 1.8:
=> {"Queen"=>1970, "AC/DC"=>1973, "Black Sabbath"=>1968, "Scorpions"=>1965,
"Ted Nugent and the Amboy Dukes"=>1967, "Van Halen"=>1972}

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

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

# Here's another way of phrasing it:
years_founded.find {|band, year_founded| year_founded >= 1970}

Using Enumerable#detect/Enumerable#find with the Optional Argument

detect/find‘s optional argument lets you specify a proc or lambda whose return value will be the result in cases where no object in the collection matches the criteria.

(Unfortunately, a complete discussion of procs and lambdas is beyond the scope of this article. I highly recommend looking at Eli Bendersky’s very informative article, Understanding Ruby blocks, Procs and methods.)

I think that the optional argument is best explained through examples…

# Once again, the array of classic rock bands
classic_rock_bands = ["AC/DC", "Black Sabbath", "Queen", \
"Ted Nugent and the Amboy Dukes", "Scorpions", "Van Halen"]

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

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

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

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

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

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

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

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

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

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

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

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

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

To see a “real” application of detect/find's optional argument, see this Ruby Quiz problem.

Categories
Uncategorized

Enumerating Enumerable: Enumerable#cycle

Welcome to another installment of Enumerating Enumerable, my series of articles in which I attempt to improve upon RubyDoc.org’s documentation for the Enumerable module. So far, I’ve covered the following methods in this series:

  1. all?
  2. any?
  3. collect / map
  4. count

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

Enumerable#cycle Quick Summary

Graphic representation of the \"cycle\" method in Ruby\'s \"Enumerable\" class.

In the simplest possible terms Given a collection, creates an infinitely-repeating ordered source of its items.
Ruby version 1.9 only
Expects An optional block to act on the items in the infinitely repeating until the break statement is encountered.
Returns An Enumerable::Enumerator that acts as the infinite source of the collection’s items.
RubyDoc.org’s entry Enumerable#cycle

Enumerable#cycle and Arrays

When used on an array and a block is provided, cycle passes each item to the block. Once the last array item has been passed to the block, cycle starts over again at the beginning of the array. cycle goes through the array forever unless it encounters a break statement in the block.

# 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

The better use for cycle is when you use it to create an object that spits out the next item in a repeating sequence.

# 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
=> #

# 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
=> # "Monday"

...

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

days.next
=> "Sunday"

days.next
=> "Monday"

How about one more example? We’ll use Enumerable‘s zip method, an array of dinner items and the “days of the week” cycle object to create a meal plan:

# 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"]]

Enumerable#cycle and Hashes

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:

  1. A two-element array, with the key as element 0 and its corresponding value as element 1, or
  2. Two separate items, with the key as the first item and its corresponding value as the second item.

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, cycle starts over again at the beginning of the hash. cycle goes through the hash forever unless it encounters a break statement in the block.

# 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

We can use the same technique that we used with arrays and use cycle 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.

# 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
=> #

# 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
=> #

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

Let’s try one more example! In this one, we’ll use cycle to create three different enumerators — two made from arrays, one from a hash — to assign cooking chores for the Enterprise-D crew for the next ten days.

# Create an enumerator for days
days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}.cycle
=> #

# 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
=> #

# Make sure we're starting from the beginning of the crew hash
crewmembers.rewind
=> #

# 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.