To begin, I am very new to Ruby on Rails.
So I want to get the data from this XML file in a hash so that the "currency" attribute of each "cube" is the key and the "rate" is the value.
First I tried using Hash.from_xml which got me the following, which looked even harder to work with:
{"Envelope"=>{"Cube"=>{"Cube"=>{"Cube"=>[{"rate"=>"1.3627", "currency"=>"USD"}, {"rate"=>"106.58", "currency"=>"JPY"}, {"rate"=>"1.9558", "currency"=>"BGN"}, {"rate"=>"25.030", "currency"=>"CZK"}, {"rate"=>"7.4414", "currency"=>"DKK"}, {"rate"=>"0.85515", "currency"=>"GBP"}, {"rate"=>"309.48",
"currency"=>"HUF"}, {"rate"=>"3.4528", "currency"=>"LTL"}, {"rate"=>"0.7037", "currency"=>"LVL"}, {"rate"=>"4.4774", "currency"=>"PLN"}, {"rate"=>"4.3528", "currency"=>"RON"}, {"rate"=>"9.0625", "currency"=>"SEK"}, {"rate"=>"1.2174", "currency"=>"CHF"}, {"rate"=>"7.7580", "currency"=>"NOK"}, {"r
ate"=>"7.5010", "currency"=>"HRK"}, {"rate"=>"42.1400", "currency"=>"RUB"}, {"rate"=>"2.4508", "currency"=>"TRY"}, {"rate"=>"1.3237", "currency"=>"AUD"}, {"rate"=>"2.3945", "currency"=>"BRL"}, {"rate"=>"1.3855", "currency"=>"CAD"}, {"rate"=>"8.6613", "currency"=>"CNY"}, {"rate"=>"10.5920", "curre
ncy"=>"HKD"}, {"rate"=>"12121.45", "currency"=>"IDR"}, {"rate"=>"5.0177", "currency"=>"ILS"}, {"rate"=>"67.1540", "currency"=>"INR"}, {"rate"=>"1529.33", "currency"=>"KRW"}, {"rate"=>"18.6867", "currency"=>"MXN"}, {"rate"=>"4.2525", "currency"=>"MYR"}, {"rate"=>"1.7152", "currency"=>"NZD"}, {"rat
e"=>"58.289", "currency"=>"PHP"}, {"rate"=>"1.7402", "currency"=>"SGD"}, {"rate"=>"42.162", "currency"=>"THB"}, {"rate"=>"11.1484", "currency"=>"ZAR"}], "time"=>"2011-11-01"}}, "subject"=>"Reference rates", "xmlns:gesmes"=>"http://www.gesmes.org/xml/2002-08-01", "Sender"=>{"name"=>"European Centr
al Bank"}, "xmlns"=>"http://www.ecb.int/vocabulary/2002-08-01/eurofxref"}}
So I ended up using ReXML:
xml = open("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml")
doc = Document.new(xml)
a = []
b = []
doc.elements.each("//Cube") do |element|
a << element.attributes["currency"]
b << element.attributes["rate"]
end
currency_rates = {}
a.each_with_index {|k,i|currency_rates[k] = b[i]}
This code works, and I get the end result that I am looking for. But to me this seems convoluted to create two separate arrays and then melding them together, is there a better way to do this? Is there a way to create my hash in the block without the arrays?
Or maybe there is a better XML query I can do before my block? I know pretty much nothing about XPath.
Using your second example you can fill the hash directly without the two intermediate arrays: