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
Selection
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}Detection
indie = jukebox.any? {|x| x.artist.hip? }Searching
Winner = contestants.find {|p| p.has_answer? }Reordering
titles = jukebox.sort_by {|x| x.title }Partitioning
quick, dead = people.partition {|p| p.can_outrun? :bear }Recombination
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.
Aboneaza-te prin RSS
Alex este freelancer, antreprenor, blogger, programator si in general pasionat de internet si tehnologie.
Un comentariu
intr-adevar, foarte elegant.