开发者

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 im开发者_JS百科plement the same functionality in my older version of ruby.


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


This guy

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

figured out you can

require 'enumerator'

and it works


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜