How to add new item to hash

前端 未结 7 1235
余生分开走
余生分开走 2020-12-22 18:44

I\'m new to Ruby and don\'t know how to add new item to already existing hash. For example, first I construct hash:

hash = {item1: 1}

after

7条回答
  •  臣服心动
    2020-12-22 19:13

    hash_items = {:item => 1}
    puts hash_items 
    #hash_items will give you {:item => 1}
    
    hash_items.merge!({:item => 2})
    puts hash_items 
    #hash_items will give you {:item => 1, :item => 2}
    
    hash_items.merge({:item => 2})
    puts hash_items 
    #hash_items will give you {:item => 1, :item => 2}, but the original variable will be the same old one. 
    

提交回复
热议问题