How to add to an existing hash in Ruby

前端 未结 7 1614
悲哀的现实
悲哀的现实 2021-01-30 00:02

In regards to adding an key => value pair to an existing populated hash in Ruby, I\'m in the process of working through Apress\' Beginning Ruby and have just fi

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 00:24

    hash = { a: 'a', b: 'b' }
     => {:a=>"a", :b=>"b"}
    hash.merge({ c: 'c', d: 'd' })
     => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 
    

    Returns the merged value.

    hash
     => {:a=>"a", :b=>"b"} 
    

    But doesn't modify the caller object

    hash = hash.merge({ c: 'c', d: 'd' })
     => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 
    hash
     => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 
    

    Reassignment does the trick.

提交回复
热议问题