使用基于日期格式的新键(作为符号)重新格式化哈希

时间:2014-02-04 22:49:17

标签: ruby

我需要转换它:

[{"day"=>"2014-02-01", "users"=>1234},
 {"day"=>"2014-02-02", "users"=>2234},
 {"day"=>"2014-02-03", "users"=>3234},
 {"day"=>"2014-02-04", "users"=>4234}]

进入这个:

[{:x=>1, y:=>1234},
 {:x=>2, y:=>2234},
 {:x=>3, y:=>3234},
 {:x=>4, y:=>4234}]

1 个答案:

答案 0 :(得分:2)

a = [{"day"=>"2014-02-01", "users"=>1234}, {"day"=>"2014-02-02", "users"=>2234}, {"day"=>"2014-02-03", "users"=>3234}, {"day"=>"2014-02-04", "users"=>4234}]

a.map.with_index(1) { |h,i| { :x => i, :y => h['users'] } }
# => [{:x=>1, :y=>1234}, {:x=>2, :y=>2234}, {:x=>3, :y=>3234}, {:x=>4, :y=>4234}]