开发者

How to split (chunk) a Ruby array into parts of X elements? [duplicate]

开发者 https://www.devze.com 2022-12-28 11:55 出处:网络
This question already has answers here: How to chunk an array in Ruby (2 answers) Closed 4 years ago. I have an array
This question already has answers here: How to chunk an array in Ruby (2 answers) Closed 4 years ago.

I have an array

foo = %w(1 2 3 4 5 6 7 8 9 10)

How can I split or "chunk" this into smaller arrays?

cl开发者_开发知识库ass Array
  def chunk(size)
    # return array of arrays
  end
end

foo.chunk(3)
# => [[1,2,3],[4,5,6],[7,8,9],[10]]


Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]


If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)
0

精彩评论

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

关注公众号