How to change the value of a step inside a loop?

I want to increase the step value in each iteration of the loop, but my solution does not work.

n=1
(0..100).step(n) do |x|
 puts x
 n+=1 
end

Is there a way to change "n" or should I use a "while loop" or smth else?

+4
source share
5 answers

I assume that you are trying to print 1, 3, 6, 10, 15, 21, etc.

step-by-step documentation says:

Iterates over a range, passing each nth element to a block. If the range contains numbers, n is added for each iteration.

What you are trying to do cannot be done with help step. A whileor traditional loop forshould do the trick.

+6
source

Enumerator Aurรฉlien Bottazini answer:

tri = Enumerator.new do |y|
  n = 0
  step = 1
  loop do
    y << n
    n = n + step
    step += 1
  end
end

tri.take(10)
#=> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

tri.take_while { |i| i < 100 }
#=> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91]
+3

, , , - while.

step = 1
last = 100
i = 0
while (i < last )
    puts i
    step += 1
    i += step
end

, , , , , , , . , , ?

+2

loop break

n = 0
step = 1
loop do
  puts n
  n = n + step
  step += 1
  break if n > 100
end
+2

, , , , , , step , step. - , - x.

0

All Articles