This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Klemme's Silent Hash
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
I’m afraid the old skool weezzard Robert Klemme is trumping flgr this month on Ruby-Talk. Both are skilled prospectors, but Klemme’s been dropping some splendorous nuggets lately. The extemporaneous challenge of the minute has been to add a block to Enumerable#uniq.
Klemme offers uniq_by:
module Enumerable
def uniq_by
h = {}; inject([]) {|a,x| h[yield(x)] ||= a << x}
end
end
He’s got a miniature Jacob’s Ladder going on inside that block. The lynch pin is that perpendicular OR-SET. He’s using it like a backwards conditional.
Here’s a simpler proof:
>> a = []; b = nil
>> b ||= a << 1
>> b ||= a << 2
>> a
=> [1]
Anyway, it’s gorgeous and he’s got it all linked up perfectly. What with a#<< returning a. And then h[] turns around and hands a back to inject. (Thanks, Glenn Parker for the tip.)