development

Ruby 배열을 X 요소의 일부로 나누는 방법은 무엇입니까?

big-blog 2020. 5. 29. 21:56
반응형

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"]]

레일을 사용하는 경우 in_groups_of 를 사용할 수도 있습니다 .

foo.in_groups_of(3)

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

반응형