From: "Stephan J. Schmidt" Date: 2002-05-29T22:12:45+09:00 Subject: Re: Idioms Thanks for your reply, I will use this. Thanks to the other people, too, I will look into the supplied URLS, bye -stephan On Wed, 2002-05-29 at 14:35, nobu.nokada@softhome.net wrote: > Hi, > > At Wed, 29 May 2002 20:58:59 +0900, > Stephan J. Schmidt wrote: > > Could someone point me to idioms about ruby, e.g. > > something shorter to > > > > if not hash.key?(key) > > hash[key] << value > > end > > If you want to add `value' only when the `hash' doesn't have > the `key': > > hash.fetch(key) {hash[key] = [value]} > > hash[key] ||= [value] > > If you want to add `value' to the `hash' with making a list > automatically: > > (hash[key] ||= []) << value > > hash.fetch(key) {hash[key] = []} << value > > hash = Hash.new([]) > hash[key] += [value] > > # 1.7 feature > hash = Hash.new {|h, i| h[i] = []} > hash[key] << value > > -- > Nobu Nakada