best process and loop in Ruby

0

I need to do a cycle within another cycle, from a total number of iterations and number of iterations per cycle, it occurred to me to do it in for and it works, I could also do it in while, but I suspect that it is not the best process. especially since I had to do an extra cycle to take into account the rest of the division.

(UPDATE)

this is the code:

puts 'KABUUM!!!'
total = gets.chomp.to_i
ciclo = gets.chomp.to_i
ciclos = total / ciclo
resto = total % ciclo
c = 0
linea = ''
for x in 1..ciclos do
linea = ''
  for y in 1..ciclo do
   c += 1
   linea << ',' if linea != ''
   linea << c.to_s 
  end
  puts linea
end
linea = ''
for n in (c + 1)..total do
   linea << ',' if linea != ''
   linea << n.to_s 
end
puts linea  if linea != ''

COMMAND LINE OUTPUT: (several results, depending on the entries)

D:\sites\ruby>ruby bucle.rb
KABUUM!!!
34
6
1,2,3,4,5,6
7,8,9,10,11,12
13,14,15,16,17,18
19,20,21,22,23,24
25,26,27,28,29,30
31,32,33,34

D:\sites\ruby>ruby bucle.rb
KABUUM!!!
25
5
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25

D:\sites\ruby>ruby bucle.rb
KABUUM!!!
22
10
1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
21,22

D:\sites\ruby>

Any idea how it can be optimized ??? in advance, thank you very much ...

    
asked by rrg1459 28.09.2017 в 20:17
source

1 answer

1

Indeed, I believe that your solution is too elaborate; The same result can be obtained using the method Enumerable # each_slice :

puts 'KABUUM!!!'

total = gets.chomp.to_i
ciclo = gets.chomp.to_i

(1..total).each_slice(ciclo) do |linea|
  puts linea.join(",")
end
  • (1..total) creates a range (which is Enumarable ).
  • each_slice returns an array with the number of elements indicated in the parameter (i.e. ciclo ) in variable linea .
  • linea.join(",") convert the returned array into a string, joining the elements with , .

I recommend that you see all the methods used by the module Enumerable of Ruby as it offers a large number of ways to iterate collections (eg ranges , hashes , arrays ) in a more idiomatic way ( for is generally avoided in Ruby ).

    
answered by 29.09.2017 / 04:29
source