简体   繁体   中英

Iterate over Ruby Array in increments of 4

I have the following array:

csv_array = [1,2,3,4,5,6,7,8,9,10]

I need to write each item in the array to a separate CSV row, in groups of 4. If I do this

CSV.open("Content_File.csv", "wb") do |csv|
    csv << csv_array
end

I get a csv file of the entire array laid out across one row.

I need my csv file to look like this:

1,2,3,4

5,6,7,8

9,10

How can I write a ruby script to say

csv << csv_array[0..3]
csv << csv_array[4..7]

And so on, regardless of how many items are in the array? I am using ruby 1.9.3.

csv_array = [1,2,3,4,5,6,7,8,9,10]

csv_array.each_slice(4) do |chunk|
  p chunk
end
# >> [1, 2, 3, 4]
# >> [5, 6, 7, 8]
# >> [9, 10]

try as

 csv_array.each_slice(4) {|a| csv.push(a)}

below:

csv_array = [1,2,3,4,5,6,7,8,9,10]
csv = []
csv_array.each_slice(4) {|a| csv.push(a)}
csv 
# => [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM