Reputation: 9848
I have the following array of arrays.
>> gold_prices
=> [["2011-01-11", "134.91"], ["2011-01-10", "134.12"],
["2011-01-07", "133.58"], ["2011-01-06", "133.83"]]
What is the cleanest way to convert each sub-array into a hash of :string => float?
Upvotes: 3
Views: 2241
Reputation: 188134
#!/usr/bin/env ruby
gold_prices = [["2011-01-11", "134.91"], ["2011-01-10", "134.12"],
["2011-01-07", "133.58"], ["2011-01-06", "133.83"]]
h = {}
gold_prices.each { | date, quote | h[date] = quote.to_f }
p h
# {"2011-01-06"=>133.83, "2011-01-07"=>133.58, ...
Upvotes: 2
Reputation: 70869
For the 4 hashes with one key you could do:
gold_prices.collect { |item| { item.first => item.last.to_f } }
Upvotes: 1
Reputation: 8313
>> gold_prices = Hash[gold_prices.map {|date, price| [date, price.to_f]}]
=> {"2011-01-11" => 134.91, "2011-01-10" => 134.12,
"2011-01-07" => 133.58, "2011-01-06" => 133.83}
Upvotes: 7