How can I initialize an Array inside a Hash in Ruby

前端 未结 3 1393
离开以前
离开以前 2020-12-28 12:22

I am trying to initialize a Hash of Arrays such as

@my_hash = Hash.new(Array.new)

so that I can:

@my_hash[\"hello\"].push(\         


        
3条回答
  •  失恋的感觉
    2020-12-28 13:01

    The argument for Hash.new is for the default value for new hash keys, so when you pass it a reference that reference will be used for new hash keys. You're updating that reference when you call...

    hash["key"].push "value"
    

    You need to pass a new reference into the hash key before pushing values to it...

    hash["key1"] = Array.new
    hash["key1"].push "value1"
    hash["key2"] = Array.new
    hash["key2"].push "value2
    

    You could try encapsulating this into a helper method as well.

提交回复
热议问题