Categories
Uncategorized

Enumerating Enumerable: Enumerable#find_index

Enumerating Enumerable

Once again, it’s Enumerating Enumerable, my series of articles in which I attempt to outdo Ruby-Doc.org’s documentation of Ruby’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’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
  11. each_with_index
  12. entries / to_a
  13. find_all / select

Enumerable#find_index Quick Summary

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

In the simplest possible terms What’s the index of the first item in the collection that meets the given criteria?
Ruby version 1.9
Expects A block containing the criteria.
Returns
  • The index of the item in the collection that matches the criteria, if there is one.
  • nil, if no item in the collection matches the crtieria.
RubyDoc.org’s entry Enumerable#find_index

Enumerable#find_index and Arrays

When used on an array, find_index passes each item in the array to the given block and either:

  • Stops when the current item causes the block to return a value that evaluates to true (that is, anything that isn’t false or nil) and returns the index of that item, or
  • Returns nil if there is no item in the array that causes the block to return a value that evaluates to true.

Some examples:

# 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

Enumerable#find_index and Hashes

When used on a hash, find_index 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.

As with arrays, find_index:

  • Stops when the current item causes the block to return a value that evaluates to true (that is, anything that isn’t false or nil) and returns the index of that item, or
  • Returns nil if there is no item in the array that causes the block to return a value that evaluates to true.

Some examples:

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"=>#<Date: 4874803/2,0,2299161>, "Freedom 7"=>#<Date: 4874849/2,0,2299161>,
"Liberty Bell 7"=>#<Date: 4875003/2,0,2299161>, "Orel"=>#<Date: 4875035/2,0,2299161>,
"Friendship 7"=>#<Date: 4875431/2,0,2299161>, "Aurora 7"=>#<Date: 4875617/2,0,2299161>,
"Sokol"=>#<Date: 4875775/2,0,2299161>, "Berkut"=>#<Date: 4875777/2,0,2299161>}

# 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 && date.month == 8}
=> 6

# The same thing, expressed a little differently
launch_dates.find_index{|launch| launch[1].year == 1962 && launch[1].month == 8}
=> 6

Using find_index as a Membership Test

Although Enumerable has a method for checking whether an item is a member of a collection (the include? method and its synonym, member?), find_index is a more powerful membership test for two reasons:

  1. include?/member? only check membership by using the == operator, while find_index lets you define a block to set up all sorts of tests. include?/member? asks “Is there an object X in the collection equal to my object Y?” while find_index can be used to ask “Is there an object X in the collection that matches these criteria?”
  2. include?/member? returns true if there is an object X in the collection that is equal to the given object Y. find_index goes one step further: not only can it be used to report the equivalent of true 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.

A quick example of this use in action:

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

Parts that Haven’t Been Implemented Yet

Ruby-Doc.org’s documentation is generated from the comments in the C implementation of Ruby. It mentions a way of calling find_index that is just like calling include?/member?:

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


Ruby 1.9 is considered to be a work in progress, so I suppose it’ll get implemented in a later release.

Categories
Uncategorized

XBox on a REALLY Big Screen

"Grand Theft Auto" on a movie screen

Here’s something for gamers who want to go big: the Cineplex chain of movie theatres in Canada is renting out downtime at 29 of its locations to people who want to play XBox 360 games on their giants screens. CDN$179 (US$169) gets you and 11 of your friends 2 hours’ worth of big screen time.

Here’s an excerpt from the CBC article:

Theatres will generally have about 12 to 24 hours of available downtime a week, mostly in the morning, she said. Many theatres are in “full grind” right now showing summer movies, but they should slow down and have more available time once school begins in September.

Theatres may also stay open late into the evening to accommodate groups, at the discretion of each manager.

“If they wanted to book a four-hour window, we could certainly go later in the evening,” [Pat Marshall, Cineplex’s vice-president of communications] said. “If the theatre manager has the staffing, they could go till two in the morning.”

The wife is a big Rock Band aficionado. Maybe I could book something for her birthday…

Categories
Uncategorized

Nine Startup Diseases and How to Cure Them

"Game Over" screen from the '80s arcade game "Battlezone"

Maybe I’m a glutton for punishment: my current job as Tech Project Manager at b5media marks the fourth startup for which I’ve worked; if you count Mackerel Interactive Multimedia — whose story, Burying the Fish, was written by Cory Doctorow for Wired but never published — I’ve worked at five. I like the “feel” of working at a startup, and now that I’ve got experience and real-world and blog-based reputations to back me up, startups are willing to pay me not only to be part of their team but to also be the “adult supervision”. At the ripe old age of 40, I’m an elder statesman in these parts (and playing an old man’s instrument only adds to that image).

That’s why I read SitePoint’s article Nine Deadly Startup Diseases—and How to Cure Them with a sense of deja vu, going through each item in their list of mistakes and saying “yup, did that one…did that one too…”

Put together, the startups for which I worked had all but one of the diseases listed in the article except for “Marketing Blind Spot”. For some reason, there was always a marketer in our midst, drumming it into our heads that marketing was necessary.

I’ve taken their list of startup diseases and cures and summarized it in the table below. For full explanations behind each disease and cure, be sure to read the article.

Startup Disease Cure
Imaginary User Syndrome: Your product isn’t targeted at anyone in particular. Establish a small, defined set of users who could benefit from your product and tailor it to them.
Frenetic Distraction Pox: Wasting time on non-essential tasks that don’t bring the business closer to break-even or profit. Focus!
Wrong Hire Infection: You’ve hired people who can’t perform or who underperform. “The smart, brave solution in those cases is amputation. Let them go gently if you want, but let them go.”
Implicit Promise Fever: You’re assuming that there are certain promises made between you and your co-founders, but you haven’t discussed them directly or put them in writing. “Have those discussions. Write the results down.”
Stealth Product Delusion: You’re waiting way too long to show your product to users while honing it to perfection (or as close to perfect as you can get). Get people to look at it! They’ll have some criticism, but that feedback is going to be very valuable.
Wrong Platform Fracture: The platform on which you’re developing (language, framework, technology) keeps getting in the way of development. Maybe you think you’ve gone too far to turn around and switch platforms. Switch platforms! ““We’ve walked this far already” isn’t a good enough reason to continue heading in that direction. Chances are, you’re much, much further from the completion of your product than you think.”
Other Interest Disorder: Other interests are pulling at you; you’re either saying “but I’m still working on my startup” and “I’ll get back to my startup soon” or working on several startups at once. Pick the project you want to work on, and break cleanly from the others.
Perfection Hallucination: You’re spending a large amount of time getting your prodcut to the point where it’s perfect, especially close to the end of the product development cycle. “Users are more forgiving of progress in the wrong direction than of a lack of progress. What you’ve built will never be perfect, but if it’s close enough your users will tell you how to improve it…Release early, release often.”
Marketing Blind Spot: You’re not doing any marketing. Do some marketing! “Marketing doesn’t have to cost much, but if you don’t do enough of it, you’re setting yourself up for failure.”
Categories
Uncategorized

“why the lucky stiff” on Why You Should Create

Why\'s photo-illustration of his book, \"why\'s (Poignant) Guide to Ruby\"
why’s (Poignant) Guide to Ruby, the most whimsical programming book ever written.

Here’s a great quote from the enigmatic programmer known only as “why the lucky stiff” on why you should create:

when you don’t create things, you become defined by your tastes rather than ability. your tastes only narrow & exclude people. so create.

Very true, especially since there are whole industries and professions that specialize in manipulating your tastes in order to get you to line other people’s pockets. Well put, why!

Categories
Uncategorized

An Illustrated Guide to the Kaminsky DNS Vulnerability

Diagram of Dan Kaminsky\'s explanation of how DNS can be \"poisoned\"

Steve Friedl has a number of excellent technical explanations on his site, and his latest one, An Illustrated Guide to the Kaminsky DNS Vulnerability, is a masterpiece that does a fine job of explaining the DNS vulnerability that Dan Kaminsky found.

Categories
Uncategorized

Copy and Paste

In the very unlikely event that you forgot what the keyboard shortcuts were…

Two wonen: one wearing a \"Copy (control + C)\" T-shirt, the other wearing a \"Paste (control + V)\" T-shirt.

Categories
Uncategorized

Linux Bloat

Slide: Linux Symposium T-shirt sizes in 1999 (mostly medium) and 2008 (mostly XL, followed by large and XXL)

It could be that programmers are getting larger, but it also could be that Linux Symposium is using American Apparel shirts. They’re supposedly not made in sweatshops and are made from really soft cotton, but they’re about a size smaller than the corresponding Hanes Beefy-T’s.