On Fri, Dec 9, 2011 at 8:38 AM, Ryan Davis <ryand-ruby / zenspider.com> wrote:
>
>
> On Dec 8, 2011, at 23:06, Mayank Kohaley <mayank.kohaley / gmail.com> 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/