The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hash#collect!

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.
Hash#collect! Posted: Mar 18, 2005 11:41 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Red Handed.
Original Post: Hash#collect!
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

It’s always bugged me that Hash#collect returns an Array. And Hash#collect! simply gags and kicks a leg. It’s another situation where we’re lacking a really smashing RCR. We’ve had Hash#collect_to_hash and Enumerable#make_hash—the latter being more favorable, right??

Gavin Sinclair’s build_hash (from extensions) is a newer version of make_hash. Like collect and map, but designed to return a Hash. Is there anything wrong with using build_hash as Hash’s own special collect?

  module Enumerable
    def build_hash
      result = {}
      self.each do |elt|
        key, value = yield elt
        result[key] = value
      end
      result
    end
  end

  class Hash
    alias collect build_hash
  end

And I’m also going to throw in Hash#collect! for your money. This method should be!! And, for the first time in years, I’m citing PoLS. I say we each get a “Go Directly To PoLS” card every age.modulo(7).zero?.

  class Hash
    def collect!( &blk )
      self.replace( build_hash( &blk ) )
    end
    alias map! collect!
  end

Read: Hash#collect!

Topic: Jason talks Basecamp with O'Reilly Previous Topic   Next Topic Topic: Ruby As Genuine Coderspeak

Sponsored Links



Google
  Web Artima.com   

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