Odd behavior from ruby Hash [duplicate]
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
精彩评论