2

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
sundar
  • 369
  • 2
  • 4
  • 10

4 Answers4

5

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
steenslag
  • 79,051
  • 16
  • 138
  • 171
1

This guy

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

figured out you can

require 'enumerator'

and it works

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
buck
  • 11
  • 1
0

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
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • thank u very much for ur reply.. In The above code, say for eg if the no. of elements is 3, it works fine for one iteration but in the second and third iteration, the name,age,sex returns nil... – sundar May 23 '11 at 10:26
0

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

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338