07 Jul 2010, 16:49
Generic-user-small

Paul Sidorov (2 posts)

Hi Chris,

Thanks for the book. I like the way you explain things about Ruby clearly and effectively. You’re a good tutor.

There’s one minor thing. I’m studying 7.3 Looping now, and I have a question on this code (your initial version):


input = ''

while input != 'bye'
    puts input
    input = gets.chomp    
end

puts 'Come again soon!'

This is your final version:


while true
    input = gets.chomp
    puts input
    if input == 'bye'
        break
    end
end
puts 'Come again soon!'

And this is mine:


input = ''

while input != 'bye'
    input = gets.chomp
    puts input
end

puts 'Come again soon!'

If you compare your first code to corrected one, you’ll notice that I only swapped puts input and input = gets.chomp. So… What’s the catch? It works exactly like your final version. I think it’s more compact, elegant and solves the problem with your initial program structure. Why did you complicated things a bit?

P.S. Sorry for my english. I’m in a constant process of mastering it:)

12 Jul 2010, 09:09
Med__2008.08.19.09.44.43_pragsmall

Chris Pine (39 posts)

Why did you complicated things a bit?

Well, in the first edition, I did not introduce “break” at all, so had to do without it in the examples. In the second edition, I tried to more closely map the english-language description of the task into ruby-code. Having “input” as some concept that exists outside the loop is somewhat counterintuitive and, arguably, not elegant at all. It feels more like a clever hack.

Intuitively, the loop is:
  1. get some input
  2. respond (conditionally, depending on input)
  3. exit the loop (conditionally, depending on input)

With break, you can actually write a loop that looks like that. (Or with a do…while() construct, but Ruby doesn’t have that.)

13 Jul 2010, 11:22
Generic-user-small

Paul Sidorov (2 posts)

Having “input” as some concept that exists outside the loop is somewhat counterintuitive and, arguably, not elegant at all.

I should agree with you. Somehow, I don’t like initializing “input” outside the loop. But this way the code is 2 lines shorter.

  You must be logged in to comment