Enumerable iterators (why I love Ruby part 2)

Got myself a sleepless night recently and killed some time reading the Rubyisms in Rails book. The chapter about Iterators was particularly pleasant, reminding me the beauty of Ruby’s Enumerable class – feels so Lisp-ish and Scheme-ish to write stuff like col.select{..}.collect{..}.join(”, “)

For the curious, here’s a cool excerpt from the book, with Enumerable’s most important methods:

Examples of Enumerable’s Higher-Level Iterators

common = bird.select {|bird, count| count > 5 }
rare = bird.reject { |bird, count| count > 5 }

Accumulation (summing up values)
sightings = birds.inject {|total, bird| total += b.count}

indie = jukebox.any? {|x| x.artist.hip? }

Winner = contestants.find {|p| p.has_answer? }

titles = jukebox.sort_by {|x| x.title }

quick, dead = people.partition {|p| p.can_outrun? :bear }

blind_dates = restaurants.zip(men, women)

Go ahead, read the docs and use Enumerable without restraints – your code will look much more beautiful and, well.. Rubyish.

Similar Posts:

Leave a Reply