Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pushing elements onto an array in a ruby Hash

Tags:

arrays

ruby

hash

In Ruby, to create a hash of arrays and push elements onto those arrays, I've seen two idioms. I'd like to know which one people prefer, and why. (Disclosure: I have my own opinion, but I want to make sure I'm not missing something obvious.)

Approach 1: use Hash's fancy initializer:

ht = Hash.new {|h,k| h[k]=[]}
ht["cats"] << "Jellicle"
ht["cats"] << "Mr. Mistoffelees"

This approach creates an empty array when you access ht with a key that doesn't yet exist.

Approach 2: simple initializer, fancy accessor:

ht = {}
(ht["cats"] ||= []) << "Jellicle"
(ht["cats"] ||= []) << "Mr. Mistoffelees"

Do people have an opinion on which one is better (or situations where one is preferred over the other)?

like image 693
fearless_fool Avatar asked Feb 15 '11 20:02

fearless_fool


1 Answers

Sometimes the hash is initially filled with data and later on it is only used to retrieve data. In those cases I prefer the first possibility, because the default proc can be "emptied" (in Ruby 1.9).

ht = Hash.new {|h,k| h[k]=[]}
ht["cats"] << "Jellicle"
ht["cats"] << "Mr. Mistoffelees"
ht["dogs"]
p ht
#=> {"cats"=>["Jellicle", "Mr. Mistoffelees"], "dogs"=>[]}

ht.default_proc = proc{}
ht["parrots"] #nil
p ht
#=> {"cats"=>["Jellicle", "Mr. Mistoffelees"], "dogs"=>[]} No parrots!
like image 186
steenslag Avatar answered Nov 15 '22 21:11

steenslag