我有以下数组数组。
>> gold_prices
=> [["2011-01-11", "134.91"], ["2011-01-10", "134.12"],
["2011-01-07", "133.58"], ["2011-01-06", "133.83"]]
将每个子数组转换为哈希值的最简洁方法是什么:string =>浮?
答案 0 :(得分:7)
>> 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}
答案 1 :(得分:2)
#!/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, ...
答案 2 :(得分:1)
对于带有一把钥匙的4个哈希,你可以做到:
gold_prices.collect { |item| { item.first => item.last.to_f } }