What I am trying to do is build a hash of arrays from an XML file:
b = Hash.new(Array.new)
h = XmlSimple.xml_in self.raw
h["data"][0]["bank"][0]["item"].each do |item|
b[item["cat"]] << item["name"]
end
This is the code, but b has like the test in irb no keys, or seems to
be empty, unless you dont know the key i advance, but that is
impossible, since the item["cat"] is dynamic and it is known of 10
categories at the moment, but it is also known that the number of
categories will go up in the future, so I want to do it future-proof
already today
> because you've never actually done x["test"]= ...
> (all you're doing is modifying the hash's default value)
OK, now I tried the following
b = Hash\.new\(Array\.new\)
h = XmlSimple\.xml\_in self\.raw
h\["data"\]\[0\]\["bank"\]\[0\]\["item"\]\.each do |item|
if b\.key? item\["cat"\]
b\[item\["cat"\]\] = item
else
b\[item\["cat"\]\] << item
You're still essentially committing the same error - you're only
setting b[item['cat'] if there is already an entry for b[item['cat']]
Did you really mean to use a hash with a single array as its default
value? (The default value stuff doesn't seem to be helping you at all,
just muddying the waters