hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Klemme's Silent Hash #

by why in bits

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

said on 31 Jan 2005 at 01:24

That’s awesome.

said on 04 Feb 2005 at 07:27

Great, the language designed for Least Surprise is getting its own Obfuscation Terrorists.

Comments are closed for this entry.