Forum: Ruby Re: what is the ruby way to do this?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
daniels (Guest)
on 2005-11-23 01:01
(Received via mailing list)
> 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.
#####################################################################################
This topic is locked and can not be replied to.