Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Sep 15 ’10

Redo vs. Retry

redo and retry are both used to re-execute parts of a loop. But they differ in how much they re-execute: redo only repeats the current iteration, while retry repeats the whole loop from the start.

redo example:

(0..5).each do |i|
  puts "Value: #{i}"
  redo if i > 2
end

The result shows, that only the last iteration is repeated:

Value: 0
Value: 1
Value: 2
Value: 3
Value: 3
Value: 3
# ... this is an infinite loop

retry example:

(0..5).each do |i|
  puts "Value: #{i}"
  retry if i > 2
end

As you can see, the whole loop starts from the beginning after a retry:

Value: 0
Value: 1
Value: 2
Value: 3
Value: 0
Value: 1
Value: 2
# ... this is an infinite loop, too

(via Ruby Loops)

21 notes 0 comments

  1. yangjindong reblogged this from rubyquicktips
  2. jackhq reblogged this from rubyquicktips
  3. tex reblogged this from rubyquicktips
  4. atm09td reblogged this from rubyquicktips
  5. nicktj reblogged this from rubyquicktips and added:
    This is pretty cool:
  6. rubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus