Ruby — Post-test loops with begin and while
A Ruby begin block followed by a while modifier runs once before testing for repetition. It is useful for simulating a first operation followed by bounded retries.
A simple example
Print first, then test
- Start with n starts at 1
- Do this Print n, add 1
- Result Stop at 4
n = 1
begin
puts n
n += 1
end while n <= 3
1 2 3
Poll until ready or the attempt limit
Count the first poll for every request, even if it is already ready. Stop after success or after the configured maximum number of attempts. The begin/end form matters. A while modifier on an ordinary expression evaluates its condition before executing that expression.
A print desk checks the printer once before deciding whether to check again. If the printer answers ready on the second check, the loop stops there. A limit of three checks keeps an offline printer from holding up the desk.
Run the example
Use Ruby 2.6 or later. Run these commands from the directory containing the example.
ruby lesson.rb
def poll_count(ready_on, limit)
attempts = 0
begin
attempts += 1
end while attempts < ready_on && attempts < limit
attempts
end
[[5, 1], [2, 3], [8, 3]].each do |ready_on, limit|
puts poll_count(ready_on, limit)
end
1 2 3
With one permitted attempt, the first case stops at 1. The second becomes ready on attempt 2. The last case never reaches readiness within its three-attempt limit.
Apply the loop to a retry queue
Simulate a job using prerecorded replies. T means a temporary failure, S means success, and X means permanent rejection. Process at most two replies per job. Stop on S or X and report how many replies were consumed.
A queue can retry a temporary failure once under a two-attempt limit. A temporary failure followed by success finishes the job. A permanent rejection stops the job immediately and leaves the next reply unused.
Run this example
Save this program as lesson.rb and run it separately.
ruby lesson.rbdef process(responses, limit)
used = 0
responses.each_char do |response|
break if used == limit
used += 1
return ['sent', used] if response == 'S'
return ['rejected', used] if response == 'X'
end
outcome = used == limit ? 'limit reached' : 'no response'
[outcome, used]
end
jobs = {'A' => 'TS', 'B' => 'XS', 'C' => 'TTS', 'D' => ''}
jobs.each do |id, responses|
outcome, attempts = process(responses, 2)
puts "#{id}: #{outcome} (#{attempts})"
end
A: sent (2) B: rejected (1) C: limit reached (2) D: no response (0)
Job A succeeds on its second reply. B stops at the rejection before its later success. C reaches the attempt limit with a success still unread. D has no recorded reply, so its count stays zero. Try raising the limit to three: only C changes, succeeding on the third reply.
Try it yourself
A request is ready on the first poll and allows three attempts. How many polls run?
Check your answer
Exactly one. The success check happens after the first poll. The example assumes a positive attempt limit.