|
Hash of Hashes Assignment Causes NoMethodError
By: Bruce Bahlmann - Contributing Author (your
feedback
is important to us!)
In rails development, you may find yourself wanting to use a hash of hashes
(HoH) for processing certain data. However a limitation within rails
generates a NoMethodError in direct assignments of multidimensional hashes. This post is about
how to work around this limitation.
Rails use of hashes, while full featured, does have problems when trying to
assign values directly to a hash of hashes. However it can be misleading as
only particular assignments generate the NoMethodError. Below you will see
the specific error case:
>> test = {} # => {}
>> test [1][2] = "dog"
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]=
Result: Doesn't work!
>> test = {} # => {}
>> test[1] = {2 => "dog"} # => {2=>"dog"}
>> test # => {1=>{2=>"dog"}}
Result: Works!
Clearly, you cannot assign a value directly to a hash of hashes. Rails
seems to only allow you to assign a value directly to a one dimensional
hash. To load the second dimension of a hash, one needs to first populate
the first dimension, at which point you can assign the second dimension
without generating the NoMethodError.
@tinv = Hash.new
@inventories.each do |inv|
yr = Time.at(inv.lmodified).strftime("%Y")
c = inv.classification_id
if @tinv[yr].nil?
@tinv[yr] = {}
end
if @tinv[yr][c].nil?
@tinv[yr][c] = {}
@tinv[yr][c] = inv.cost.to_f
else
@tinv[yr][c] += inv.cost.to_f
end
end
The code above provides a loop creating a hash of hashes used for counting
costs by year. To make this work, first you need to create the base hash
record for each year (you only need to do this once for each year - when it
is undefined or nil). Beyond that, a similar exercise is needed for each
yearly classification, however unlike year, you have two cases - create the
first instance and add to the previously stored value.
Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
|
|
|
(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.
|