在Ruby中修改Array的形式

时间:2014-11-19 14:24:00

标签: ruby arrays hash

我希望有人可以提供帮助。

我通过调用Google电子表格返回了一个数组,该电子表格返回如下:

{"2014 week"=>"01", "Weekly reach"=>"2.93"}
{"2014 week"=>"02", "Weekly reach"=>"3.37"}
{"2014 week"=>"03", "Weekly reach"=>"3.24"}
{"2014 week"=>"04", "Weekly reach"=>"2.39"}
{"2014 week"=>"05", "Weekly reach"=>"2.96"}
{"2014 week"=>"06", "Weekly reach"=>"6.31"}
{"2014 week"=>"07", "Weekly reach"=>"9.11"}
{"2014 week"=>"08", "Weekly reach"=>"8.59"}
{"2014 week"=>"09", "Weekly reach"=>"2.11"}
{"2014 week"=>"10", "Weekly reach"=>"2.24"}
{"2014 week"=>"11", "Weekly reach"=>"1.88"}
{"2014 week"=>"12", "Weekly reach"=>"2"}
{"2014 week"=>"13", "Weekly reach"=>"3"}
{"2014 week"=>"14", "Weekly reach"=>"2"}
{"2014 week"=>"15", "Weekly reach"=>"2"}
{"2014 week"=>"16", "Weekly reach"=>"3"}

基本上,我想将此数组修改为以下形式:

  

result = [{x:1,y:2.93},{x:2,y:3.37},{x:3,y:3.24} ...]

由于我在Ruby中的 noob 状态我很难挣扎,但相信解决方案在于 arr.map!,如果我真正理解的话就不会#&# 39; t需要这个问题!任何帮助都将非常感激。

2 个答案:

答案 0 :(得分:1)

map返回由每个元素的块评估结果组成的数组。所以你应该:

result = array.map do |data|
  {
    x: data['2014 week'],
    y: data['reach']
  }
end

答案 1 :(得分:0)

Marek Lipka是对的 - 我记得当我无法弄清楚地图时,所以这里有一个更彻底的解释。

他的回答与此代码相同,假设array定义如下:

array = [
  {"2014 week"=>"01", "Weekly reach"=>"2.93"},
  {"2014 week"=>"02", "Weekly reach"=>"3.37"},
  {"2014 week"=>"03", "Weekly reach"=>"3.24"},
  {"2014 week"=>"04", "Weekly reach"=>"2.39"},
  {"2014 week"=>"05", "Weekly reach"=>"2.96"},
  {"2014 week"=>"06", "Weekly reach"=>"6.31"},
  {"2014 week"=>"07", "Weekly reach"=>"9.11"},
  {"2014 week"=>"08", "Weekly reach"=>"8.59"},
  {"2014 week"=>"09", "Weekly reach"=>"2.11"},
  {"2014 week"=>"10", "Weekly reach"=>"2.24"},
  {"2014 week"=>"11", "Weekly reach"=>"1.88"},
  {"2014 week"=>"12", "Weekly reach"=>"2"},
  {"2014 week"=>"13", "Weekly reach"=>"3"},
  {"2014 week"=>"14", "Weekly reach"=>"2"},
  {"2014 week"=>"15", "Weekly reach"=>"2"},
  {"2014 week"=>"16", "Weekly reach"=>"3"},
]

result = []
array.map do |data|
  result << { x: data['2014 week'], y: data['reach'] }
end
return result

所以map正在做与每个完全相同的事情,但是把它做的任何结果推到一个数组中,所以你不必这样做。

希望有助于解释它,但请注意马雷克的答案 - 这对评论来说太长了