开发者

Odd behavior from ruby Hash [duplicate]

开发者 https://www.devze.com 2023-03-15 01:42 出处:网络
This question already has answers here: Strange, unexpected behavior (disappearing/changing values) when using Hash default value, e.g. Hash.new([])
This question already has answers here: Strange, unexpected behavior (disappearing/changing values) when using Hash default value, e.g. Hash.new([]) (4 answers) Closed 3 years ago.

I'm getting some rather unexpected behavior from hashes in ruby

here's a simplified demonstration of the problem

estdata = ["a","b","c"]
outputHash = Hash.new({:IDs => [], :count => 0})

estdata.each do |x|
  outputHash[x][:IDs] << x
  outputHash[x][:count] +=1
end

p outputHash # => {}
p outputHash["a"] # => {:count=>3, :IDs=>["a"开发者_如何转开发, "b", "c"]}

So firstly, why does the first p output an empty hash when clearly outputHash isn't empty?

And secondly and much more to my frustration and confusion, why does is seem that every key in the has points to a single value (the hash containing the :count and :IDs keys) and how would I get around this?


With Hash.new and a parameter everything will point to the same object.

>> h = Hash.new('hello') #=> {}
>> h[:a] #=> "hello"
>> h[:a].object_id #=> 2152871580
>> h[:b].object_id #=> 2152871580
>> h[:c].object_id #=> 2152871580

What you want is the block form:

>> h = Hash.new { |h,k| h[k] = {} } #=> {}
>> h[:a].object_id #=> 2152698160
>> h[:b].object_id #=> 2152627480
0

精彩评论

暂无评论...
验证码 换一张
取 消