Re: what is the ruby way to do this?


#1

thank you. this assumes that the hash’s default value is nil.
but this is a good enough assumption for my purposes. i was
hoping to avoid creating one-element arrays and still have
the simplicity of a single line solution but i guess this
cant be done. thanks for your help.

You can always convert it out at the end.

hash = Hash.new{|h,k|h[k]=[]}
hash[“monkey”] << “banana”
hash[“monkey”] << “sugar”
hash[“dog”] << “water”
hash = hash.inject({}) {|s,x|k,v=*x; s[k] = (v.size == 1 ? v[0] : v); s}
=> {“dog”=>“water”, “monkey”=>[“banana”, “sugar”]}
#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################