programing

Ruby 배열을 X 요소의 일부로 분할(청크)하는 방법은 무엇입니까?

iphone6s 2023. 5. 27. 09:55
반응형

Ruby 배열을 X 요소의 일부로 분할(청크)하는 방법은 무엇입니까?

나는 배열을 가지고 있습니다.

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

어떻게 하면 이를 더 작은 어레이로 분할하거나 "청크"할 수 있습니까?

class Array
  def chunk(size)
    # return array of arrays
  end
end

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

Enumerable #each_slice를 확인합니다.

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

레일을 사용하는 경우 다음의 _groups_에서도 사용할 수 있습니다.

foo.in_groups_of(3)

언급URL : https://stackoverflow.com/questions/2699584/how-to-split-chunk-a-ruby-array-into-parts-of-x-elements

반응형