sundar
sundar

Reputation: 389

Is there an equivalent of Array#each_slice() in Ruby 1.8.5?

I'm using ruby 1.8.5, and the each_slice() method for an array is not working.

My code is something like:

array.each_slice(3) do |name,age,sex|   .....   end

Is there any other way to implement the same functionality in my older version of ruby.

Upvotes: 2

Views: 486

Answers (4)

steenslag
steenslag

Reputation: 80065

Bake your own:

module Enumerable
  def each_slice( n )
    res = []
    self.each do |el|
      res << el
      if res.size == n then
        yield res.dup
        res.clear
      end
    end
    yield res.dup unless res.empty?
  end
end

Upvotes: 5

buck
buck

Reputation: 11

This guy

http://tekhne.wordpress.com/2008/02/01/whence-arrayeach_slice/

figured out you can

require 'enumerator'

and it works

Upvotes: 1

Andrew Grimm
Andrew Grimm

Reputation: 81520

I haven't used it myself, but consider using the backports gem.

Upvotes: 0

fl00r
fl00r

Reputation: 83680

I haven't got 1.8.5, but you can try this

0.step(array.size, 3) do |i|
  name, age, sex = array[i], array[i+1], array[i+2]
  ...
end

Upvotes: 0

Related Questions