Joel VanderWerf
1/2/2007 6:40:00 PM
Johannes Fredborg wrote:
> Okay guys!
> I am pritty new to Ruby programing and i need your help.
>
> Is it possibel to ask the program to go back to another program line
> number and then proceed from there?
>
> an exampele:
>
> ans1 = gets.chomp <----------------- (proceed from here)
> if ans1 == 'black'
> co1 = 0
> puts
> puts 'type in the next color'
> ans2 = gets.chomp
> end
>
> if ans1 == 'brown'
> co1 = 1
> puts
> puts 'type in the next color'
> ans2 = gets.chomp
> end
>
> if co1 == nil
> puts
> puts 'Not acepted, please retype the color'
> goto.line 1 <------------------------------ (this was just a wild wild
> guess)
> end
> ...
> ...
>
> Do you see what i mean? is this possibel to do. Or is there another way
> that I can achieve the same effect?
One way is to use the "redo" keyword. However, it only works within a
do-end block. Here's an example:
$ cat redo.rb
1.times do
print "input: "
ans = gets.chomp
if ans == 'foo'
puts "bad input: #{ans}"
redo
end
puts "good input: #{ans}"
end
$ ruby redo.rb
input: foo
bad input: foo
input: foo
bad input: foo
input: bar
good input: bar
It is a bit strange to go into a "1.times" loop just so that we can use
the "redo" keyword. (Actually, we could use a while-end block, but that
would be awkward too.) If you like, you can write your own iterator in
place of #times, like so:
def in_redo_context
yield
end
in_redo_context do
print "input: "
ans = gets.chomp
if ans == 'foo'
puts "bad input: #{ans}"
redo
end
puts "good input: #{ans}"
end
This approach uses a block for each line you want to return to. So this
will start to get messy if you have lots different place to return to,
since you will need nested blocks. In that case, you might want to
consider James's suggestion of continuations.
Another approach is to use exceptions:
class BadInput < StandardError; end
begin
print "input: "
ans = gets.chomp
if ans == 'foo'
raise BadInput, "bad input: #{ans}"
end
puts "good input: #{ans}"
rescue BadInput => ex
puts ex.message
retry
end
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407