Convert an array of string arrays to a hash of string and float in Ruby?
I have the following array of arrays.
>> gold_prices
=> [["2011-01-11", "134.91"], ["2011-01-10", "134.12"],
["2011-01开发者_StackOverflow中文版-07", "133.58"], ["2011-01-06", "133.83"]]
What is the cleanest way to convert each sub-array into a hash of :string => float?
>> 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}
#!/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, ...
For the 4 hashes with one key you could do:
gold_prices.collect { |item| { item.first => item.last.to_f } }
精彩评论