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)?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With