From: Robert Klemme Date: 2011-12-09T18:23:02+09:00 Subject: Re: How can I do h["foo"] += "bar" if h["foo"] does not exist? On Fri, Dec 9, 2011 at 8:38 AM, Ryan Davis wrote: > > > On Dec 8, 2011, at 23:06, Mayank Kohaley wrote: > >> You can have something like this to check whether the key is present or >> not- >> >> h["key"] += value if h["key"] > > Values can be false/nil. Also, this is inelegant. Either do this to prevent accidental modification of the default object: irb(main):006:0> h = Hash.new("".freeze) => {} irb(main):007:0> h[:e] += "foo" => "foo" irb(main):008:0> h[:f] += "bar" => "bar" irb(main):009:0> h => {:e=>"foo", :f=>"bar"} irb(main):010:0> h[:f] += "foo" => "barfoo" irb(main):011:0> h => {:e=>"foo", :f=>"barfoo"} Or, what I'd consider better because it is more efficient, use String#<< to append and not create new instances all the time: irb(main):012:0> h = Hash.new {|ha,k| h[k] = ""} => {} irb(main):013:0> h[:e] << "foo" => "foo" irb(main):014:0> h[:f] << "bar" => "bar" irb(main):015:0> h => {:e=>"foo", :f=>"bar"} irb(main):016:0> h[:f] << "foo" => "barfoo" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/