I often duck punch this:

class Hash
  def self.auto(&block)
    Hash.new do |h,k|
      h[k] = block.arity == 1 ? yield(k) : yield
    end
  end
end

so that:
things_by_key = Hash.new{|h,k| h[k] = []}

becomes
things_by_key = Hash.auto { [] }

You can even nest them without hurting yourself

deep_things = Hash.auto {
                           Hash.auto { 0 }
                      }

A general, fast y-combinator'd be nice i guess, but this often does the trick

:lachie
http://smartbomb.com.au
http://www.flickr.com/photos/lachie/



On Tue, Mar 10, 2009 at 4:37 PM, Clifford Heath
<[email protected]> wrote:
>
> On 10/03/2009, at 4:15 PM, Daniel N wrote:
>> One of the things I like with hashes is default values set with
>> procs :)
>>
>> things_by_key = Hash.new{|h,k| h[k] = []}
>> things.each do |thing|
>>   things_by_key[thing.key] << thing
>> end
>>
>> I use these all the time for default values in all sorts of ways :)
>
> I don't prefer that. The syntax requires more knowledge, and
> the result isn't faster (is it? possibly it avoids two hash() calls?).
> Also the fact that the default isn't present where you add entries
> tends to engender the mistake of direct assignment instead of
> the correct initialize sequence.
>
> Possibly if you defined:
>
> class Hash
>   def self.new_to_array
>     new{|h,k| h[k] = [] }
>   end
> end
>
> so you can say
>
>> things_by_key = Hash.new_to_array
>> things.each do |thing|
>>   things_by_key[thing.key] << thing
>> end
>
> ... I'd be less fussed by those differences.
>
> Clifford Heath.
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
or Rails Oceania" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rails-oceania?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to