开发者

Convert an array of string arrays to a hash of string and float in Ruby?

开发者 https://www.devze.com 2023-02-03 18:24 出处:网络
I have the following array of arrays. >> gold_prices => [[\"2011-01-11\", \"134.91\"], [\"2011-01-10\", \"134.12\"],

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 } }
0

精彩评论

暂无评论...
验证码 换一张
取 消