The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Klemme's Silent Hash

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Klemme's Silent Hash Posted: Jan 30, 2005 10:56 PM
Reply to this message Reply

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
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded

Advertisement

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

Read: Klemme's Silent Hash

Topic: Do NOT Reverse Lookup Previous Topic   Next Topic Topic: Starmonkeys at the Office

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use