JP Silvashy
JP Silvashy

Reputation: 48495

Ruby, skip items while looping over an array?

Say I have an array like so:

[ 
  {"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}
]

And I want to loop over it putting every x items in a new array, so like say I wanted to write a method that took an argument something like my_arr.skip(5) or something? I'm a little stuck here, and don't know how to proceed. Any help at all would be hugely appreciated.

Upvotes: 1

Views: 1065

Answers (2)

daxelrod
daxelrod

Reputation: 2589

If you want to end up with an array of the first five items, an array of the second five items, etc, you want Enumerable#each_slice

Upvotes: 1

numbers1311407
numbers1311407

Reputation: 34072

Enumerable#each_slice is probably what you want:

# 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]]  

Upvotes: 6

Related Questions