Ruby every logical question

I am trying to solve a simple Ruby problem from Seven languages ​​in seven weeks

Print the contents of the array of sixteen numbers, four numbers at a time, using only each

Here is what I came up with: can this be done in a simple way or can it be done better?

a = (1..16).to_a

i = 0
j = []
a.each do |item|
  i += 1 
  j << item
  if(i % 4 == 0)
    p j
    j = []
  end
end

This can be done using each_sliceone line.

a.each_slice(4){|x| p x}

+5
source share
8 answers

Thea, your decision is fine. Since you need to use each, the complexity of the algorithm will be limited by the size of your array.

I came up with a solution below. This is the same idea, except that it does not use aux var (j) to store partial results.

i = 0
a.each do |item|
  p a[i, 4] if(i % 4 == 0)
  i +=1
end
+6

, , ( , ). :

(0...a.size).each {|index| p a[index, 4] if index % 4 == 0}

, 18:

>> a = (113..150).to_a.insert(5,55).insert(10,66666).shift(18)
=> [113, 114, 115, 116, 117, 55, 118, 119, 120, 121, 66666, 122, 123, 124, 125, 126, 127, 128]
>> (0...a.size).each {|index| p a[index, 4] if index % 4 == 0}
[113, 114, 115, 116]
[117, 55, 118, 119]
[120, 121, 66666, 122]
[123, 124, 125, 126]
[127, 128]
=> 0...18
+2

, :

x = 4
(0...(a.size/x.to_f).ceil).each {|i| p a.slice(x*i,x)}
+1

:

(1..16).each do |item|
  print "#{item} "
  print "\n" if item % 4 == 0
end
0

, ... , 16 .

##########
# Method 1 - Store chunks of 4 and print at the end
##########
a = (1..16).to_a
b = []
a.each do |item|
    b << [] if b.size == 0
    b << [] if b[-1].size == 4
    b[-1] << item
end

# choose your desired printing method
print b 
b.each{|c| puts c.join(",")}

##########
# Method 2 - print the chunks as they are encountered
##########

# Note: "p" was specifically chosen over "print" because it returns the value printed instead of nil.
#       If you use a different printing function, make sure it returns a value otherwise the 'b' array will not clear.


# Note: This implementation only prints out all array entries if a multiple of 4
#       If 'b' contains any items outside the loop, they will not be printed
a = (1..16).to_a
b = []
a.each do |item|
    b << item
    b = [] if b.size == 4 and puts b
end


# Note: This implementation will print all array elements, even if number of elements is not multiple of 4.
a = (1..16).to_a
b = []
a.each do |item|
    b = [] if b.size == 4 and p b
    b << item
end
p b
0

- , :

array = (1..16).to_a
i = 0
array.each do
  puts array[i...i+4].to_s if i % 4 == 0 and i+4 <= array.size
  i+=4 
end
0

each_with_index? , @Miguel :

a.each_with_index do |item, i|
  p a[i, 4] if i.modulo(4).zero?
end

i % 4 == 0 , ( "i modulo 4 is zero" )

0

:

a.each {|i| p a[i,4] if (i+3) % 4 == 0}
0

All Articles