Reputation: 27497
I have to create XML that looks something like this:
<?xml version="1.0" ?>
<FirstLevel>
<Package>
<Name></Name>
</Package>
<Package>
<Name></Name>
</Package>
...
</FirstLevel>
As you can see, Package
shows up multiple times at the same level in the structure.
I know you can't have duplicate keys in a Ruby hash, so I don't know how I would be able to go from a hash to XML when there are duplicate keys. Does anyone have any ideas?
I'm using Hash#to_xml
to convert my hash to XML (made available by ActiveSupport I believe).
By the way, I'm using Rails.
Upvotes: 1
Views: 920
Reputation: 27497
Okay I believe I figured it out. You have to use Hash#compare_by_identity
. I believe this makes it so that the key lookups are done using object id as opposed to string matches.
I found it in "Ruby Hash with duplicate keys?".
{}.compare_by_identity
h1 = {}
h1.compare_by_identity
h1["a"] = 1
h1["a"] = 2
p h1 # => {"a"=>1, "a"=>2}
Upvotes: 3