How to add new item to hash

前端 未结 7 1193
余生分开走
余生分开走 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:01

    Create hash as:

    h = Hash.new
    => {}
    

    Now insert into hash as:

    h = Hash["one" => 1]
    
    0 讨论(0)
  • 2020-12-22 19:05

    If you want to add new items from another hash - use merge method:

    hash = {:item1 => 1}
    another_hash = {:item2 => 2, :item3 => 3}
    hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}
    

    In your specific case it could be:

    hash = {:item1 => 1}
    hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}
    

    but it's not wise to use it when you should to add just one element more.

    Pay attention that merge will replace the values with the existing keys:

    hash = {:item1 => 1}
    hash.merge({:item1 => 2}) # {:item1=>2}
    

    exactly like hash[:item1] = 2

    Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:

    hash = {:item1 => 1}
    hash.merge!({:item2 => 2})
    # now hash == {:item1=>1, :item2=>2}
    
    0 讨论(0)
  • 2020-12-22 19:05

    hash.store(key, value) - Stores a key-value pair in hash.

    Example:

    hash   #=> {"a"=>9, "b"=>200, "c"=>4}
    hash.store("d", 42) #=> 42
    hash   #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
    

    Documentation

    0 讨论(0)
  • 2020-12-22 19:10

    Create the hash:

    hash = {:item1 => 1}
    

    Add a new item to it:

    hash[:item2] = 2
    
    0 讨论(0)
  • 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. 
    
    0 讨论(0)
  • 2020-12-22 19:15

    hash[key]=value Associates the value given by value with the key given by key.

    hash[:newKey] = "newValue"
    

    From Ruby documentation: http://www.tutorialspoint.com/ruby/ruby_hashes.htm

    0 讨论(0)
提交回复
热议问题