Restarting a loop from the top - ruby

I have the following:
text_counter = 0
MAXTEXT_COUNTER = 10
puts "hello, this will start"
loop do
puts "hello"
text_counter += 1
sleep(2)
if text_counter >= MAXTEXT_COUNTER
break
end
end
sleep(7200)
print "ended test"
Once the break has happened, how can I get it to start again from the top?
I'm now thinking I could nest this loop in an until loop with the condition of text_counter == 1000. This would break, then sleep for 2 hours, then start again until it hits 1000.

It looks like you need a loop within a loop where you repeat one N times, the other M times:
MAXTEXT_COUNTER = 10
puts "hello, this will start"
loop do
MAXTEXT_COUNTER.times do
puts "hello"
sleep(2)
end
print "ended test"
sleep(7200)
end
The outer loop is perpetual. The inner one runs a certain number of times and stops using the times method.

You're looking for next
It functions similarly to break, but returns control back to the top of the loop. It's great for creating flat control flow.
For example
0.upto(100) do |i|
if i % 7 == 0
puts "#{i} is a multiple of 7"
next
end
puts i
end

There is a retry keyword which repeats the loop from top, just what you've asked.
Or you can wrap your loop into a method and continuously call that method.

Related

Ruby Countdown loop Learn Lab

I am currently working on a lab to create a countdown timer using a while loop and the subtract/assign operator. So far I have the loop counting 10 and breaking to 0 and printing my string "Happy New Year". I am not sure why it isn't iterating from 10 down to 0. Link to lab and code below https://learn.co/tracks/online-software-engineering-structured/procedural-ruby/looping/countdown-to-midnight-lab
number = 10
while number > 0
puts "#{number} SECOND(S)!"
number -= 1
break if n <= 0
puts "HAPPY NEW YEAR!"
end
end
There is one end too much. Proper indentation could have told you that.
puts "HAPPY NEW YEAR!" should probably be the last line, out of the loop (and probably without the puts).
n should be number
The task is in the form of a method which returns a string . puts however returns nil.

cant understand the triagle number enumerator yielder yield

unable to understand this code how it works.
triangular_numbers = Enumerator.new do |yielder|
number = 0
count = 1
loop do
number += count
count += 1
yielder.yield number
end
end
5.times { print triangular_numbers.next, " " }
cant understand how yielder works for this block. how its yield work for number variable. how do loop runs 5 times. and how triangular_number.next works for the first time.
An enumerator is basically something that you can call next on and get something back. The yielder is the mechanism where it gives something back when next is called. Execution stops at the yield until the next call to next.
Farfetched analogy
You can think of an enumerator as a ticket machine like when you're waiting in line at a government office. When you press a button (next) it gives you a ticket. Inside the machine there's a chute where the ticket comes out. But the ticket machine is not constantly printing tickets. It waits for the button to be pressed before it prints the next ticket and puts it through the chute.
In this case the analogous code would be:
ticket_machine = Enumerator.new do |chute|
ticket = 0
loop do
#print_ticket
chute.yield ticket #waits here until you hit the button
ticket += 1
end
end
5.times { print ticket_machine.next, " " } # gets 5 tickets
Your code sample is basically the same thing, but instead of issuing tickets, it's issuing triangular numbers. The chute is the yielder where the numbers get passed through.
This is not the only way to use an enumerator, check the docs for more.
Enumerator::new accepts a block. This block, when run, receives an Enumerator::Yielder, which has a method #yield.
When the Enumerator#next is called, the block is executed, up to the first Enumerator::Yielder#yield. The execution is paused there; the value given to yield is the value that next returns. When you call next again on the same Enumerator, the execution is resumed, and proceeds until it encounters yield again.
So in your case, 5.times executes its block, intending to repeat it five times. triangular_numbers.next is called; this starts the execution of the block above. number and count are set to their values, and an infinite loop is started. number is set to 1, count is set to 2, and then we find yielder.yield. This pauses the execution of the block, and returns the control back to where next was called inside 5.times loop. next returns 1, because yielder.yield received number (1).
Second time through the 5.times loop, we want to print the next number. This stops the main execution line, and resumes the enumerator block from just after yielder.yield. The infinite loop continues; number is 3, count is 3, yielder.yield pauses the enumerator and resumes the main code. next gets 3, which gets printed.
Third, fourth and fifth time through the 5.times loop are exactly the same.
After five iterations, 5.times loop ends, and the execution proceeds past it. The enumerator is paused, ready to give the next number in sequence, if you ever call next on it again (since it has an infinite loop), but you never do, and the program exits.
I'll try to explain what it does bit by bit, so you can try to wrap your head around it.
Enumerator.new do |yielder|
end
So you instantiate an enumerator that will work over a variable called yielder.
Inside its scope you set some local vars (that will be kept as the object is reused):
number = 0
count = 1
And then you set a loop that increments number by count and count by 1 and then call yield over your argument passing number to it as an argument.
loop do
number += count
count += 1
yielder.yield number
end
5.times repeats the block passed to it 5 times. The block
-> { print triangular_numbers.next, " " }
calls print that takes n args and concatenates the parts to form a string, but does not append a newline.
The first argument is our enumerator next interaction (triangular_numbers.next), which will compute the current number and call yield on the Enumerator::Yielder that's implicitly created handling the control back to the calling Fiber along with any args that got passed to it.
(All Enumerators are implemented as "Fibers" on MRI)
So that yielder.yield call is similar to a Fiber.yield call and will allow the 5.times loop to run and return the number 1.
I'm adding a piece of code to the already clear explanation provided:
my_enum = Enumerator.new do |whatever_name_for_the_yielder|
n = 0
loop do
whatever_name_for_the_yielder.yield "Return this: #{n}"
n += 1
end
end
puts my_enum.next #=> Return this: 0
puts my_enum.next #=> Return this: 1
puts my_enum.next #=> Return this: 2
When you provide an end to the iteration, it stops with an error:
my_enum2 = Enumerator.new do |whatever_name_for_the_yielder|
2.times do |n|
whatever_name_for_the_yielder.yield "Return this: #{n}"
end
puts "Outside the loop"
end
puts my_enum2.next #=> Return this: 0
puts my_enum2.next #=> Return this: 1
puts my_enum2.next #=> Outside the loop
#=> ERROR: .....in `next': iteration reached an end (StopIteration)

Reading input from user without interrupting program execution

Im trying to do a loop in ruby that display a number + 1 every second. Id like the user to be able to input when he want. the problem is that i have to input something for the loop to continue. sorry for my bad english im fr
p.s im using a online compiler (repl.it)
You can accomplish what you want using threads and some simple state variables to communicate between the threads.
In this example we use a variable #stop to signal from the main thread to the counting thread when it's time to end the counting loop.
This example works on repl.it directly:
https://repl.it/repls/RingedIlliterateEnglishsetter
Hopefully this gives you some ideas on how to proceed.
#stop = false
thr = Thread.new {
puts "Counting thread starting..."
i = 0
loop {
i += 1
puts i
sleep 1
break if #stop
}
puts "Counting thread exit..."
}
loop {
puts "\nWaiting for input...\nType 'stop' to exit..."
input = gets.chomp
if input == "stop"
puts "Stopping..."
#stop = true
break
end
}
# Wait for counting thread to end
thr.join
puts "Main program exit..."

Callback after every `each` iteration when `next` is called

I want to run some code after every iteration of each. Is there a way to do this without repeating the code? I tried this:
(1..10).each do |n|
continue = Proc.new {
puts "ended #{n}"
next
}
continue.call if n == 2
puts n
continue.call
end
but it didn't work.
In my actual code, I have lots of next calls. That's why it's unpractical to call a method every time I call next.
Approach 1
Define the contents of the loop in a method that you call from the loop. You can put an ensure block in the method. That way, your method can use return anywhere you want to move onto the next iteration, but you still guarantee you execute the ensure code:
def doit(x)
return if x == 2
puts "I like the number #{x}"
ensure
puts "LOOP"
end
[1,2,3,4].each{|x| doit(x)}
results in
I like the number 1
LOOP
LOOP
I like the number 3
LOOP
I like the number 4
LOOP
Approach 2
Similar to approach 1, but allows you reuse the "callback" code for different concerns. It also keeps you using next instead of return. This is to define a method that yields and then does other stuff:
def ensure_LOOP(x)
yield
puts "LOOP"
end
[1,2,3,4].each do |x|
ensure_LOOP(x) do
next if x == 2
puts "I really like the number #{x}"
end
end
Results in
I really like the number 1
LOOP
LOOP
I really like the number 3
LOOP
I really like the number 4
LOOP
And
[1,2,3,4].each do |x|
ensure_LOOP(x) do
next unless x == 2
puts "I don't like the number #{x}"
end
end
results in
LOOP
I don't like the number 2
LOOP
LOOP
LOOP
As I understand the question, you don't want anything executed after continue.call if n==2. If that's correct, you could use the control expression next with an argument.
def m(n)
puts "Only #{n} more days!"
end
(1..6).each do |n|
next m(n) if n==3
puts n
m(n)
end
1
Only 1 more days!
2
Only 2 more days!
Only 3 more days!
4
Only 4 more days!
5
Only 5 more days!
6
Only 6 more days!
Just call it within the each loop?
(1..10).each do |n|
puts n
puts "ended #{n}"
end
The code you provided actually does run, and outputs the following:
1
ended 1
ended 2
2
ended 2
3
ended 3
4
ended 4
5
ended 5
6
ended 6
7
ended 7
8
ended 8
9
ended 9
10
ended 10
As you can see, the Proc gets called twice for the number 2, as your if condition passes in that case and calls the Proc.
Stepping back, defining a method outside the context of the iteration is probably a better choice. It will make the code easier to read and avoid redefining the Proc each time the each block executes.
That said, technically what you have here seems to run okay.

Terminating Loop on Input

I'm trying to find a way to terminate a loop when the user hits 'x'+Enter. I want the loop to just keep running in the background until the user cancels it.
Something along these lines:
while gets.chomp != 'x'
puts 'looping...'
sleep 1
end
I'm a beginner with programming and have searched far and wide for how to do this so any help would be deeply appreciated.
You have to use threads for this:
Thread.new do
while line = STDIN.gets
break if line.chomp == 'x'
end
exit
end
# whatever you want to do in the background
# (or rather in the foreground, actually)
loop do
puts "foo"
sleep 1
end
The problem is that STDIN.gets blocks, so you can't do something else at the same time without parallelizing the program by using a background thread that only checks for input.

Resources