Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format an array to break every five elements into new line in ruby?

Tags:

arrays

ruby

So I have an array. I want to take the first elements and break them into new line. So my array is =

a = [0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

How do I print it as

00000
00000
00000
00000
00000

Thanks.

like image 917
psharma Avatar asked Dec 08 '22 17:12

psharma


2 Answers

Just use the each_slice method of the Enumerator class to split your original array into arrays that consist of five elements each and the join method of the Array class to convert the five element arrays to strings:

a.each_slice(5) { |x|
  puts x.join
}
like image 168
Fabian Winkler Avatar answered Dec 11 '22 11:12

Fabian Winkler


a.each_index do |i|
  puts if i%5 == 0
  print a[i]
end
like image 36
Arindam Avatar answered Dec 11 '22 10:12

Arindam