Ruby,在循环数组时跳过项目?

时间:2011-09-11 04:03:26

标签: ruby arrays

说我有一个这样的数组:

[ 
  {"timestamp"=>"1", "count"=>4488.0},
  {"timestamp"=>"2", "count"=>4622.0},
  {"timestamp"=>"3", "count"=>4655.0},
  {"timestamp"=>"4", "count"=>4533.0},
  {"timestamp"=>"5", "count"=>4439.0},
  {"timestamp"=>"6", "count"=>4468.0},
  {"timestamp"=>"7", "count"=>4419.0},
  {"timestamp"=>"8", "count"=>4430.0},
  {"timestamp"=>"9", "count"=>4429.0},
  {"timestamp"=>"10", "count"=>4502.0},
  {"timestamp"=>"12", "count"=>4497.0},
  {"timestamp"=>"13", "count"=>4468.0},
  {"timestamp"=>"14", "count"=>4510.0},
  {"timestamp"=>"15", "count"=>4547.0},
  {"timestamp"=>"16", "count"=>4471.0},
  {"timestamp"=>"17", "count"=>4501.0},
  {"timestamp"=>"18", "count"=>4451.0},
  {"timestamp"=>"19", "count"=>4453.0},
  {"timestamp"=>"20", "count"=>4593.0},
  {"timestamp"=>"21", "count"=>4540.0},
  {"timestamp"=>"22", "count"=>4516.0},
  {"timestamp"=>"23", "count"=>4494.0}
]

我想循环它将每个x项放在一个新数组中,所以就像说我想编写一个带有类似my_arr.skip(5)之类的参数的方法?我有点卡在这里,不知道该怎么办。任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:6)

Enumerable#each_slice可能就是你想要的:

# it returns an enumerator, so you could look over it and do whatever
> [1, 2, 3, 4].each_slice(2) {|s| puts s.inspect }
[1, 2]
[3, 4]

# or if you're just looking to group into smaller arrays, you could just...
> [1, 2, 3, 4].each_slice(2).to_a
[[1, 2], [3, 4]]  

答案 1 :(得分:1)

如果你想得到前五个项目的数组,后五个项目的数组等,你想要Enumerable#each_slice