From: tamouse mailing lists Date: 2013-02-19T12:11:03+09:00 Subject: Re: Deaf Grandma On Mon, Feb 18, 2013 at 6:18 PM, fishina barrel wrote: > Matthew Kerwin wrote in post #1097695: >> Matthew Kerwin wrote in post #1097694: >>> If it was me, I'd probably replace the 'while' statement with 'loop do', >>> and after Granny says goodbye (inside the if-end block) I'd add a >>> 'break'. I think that just makes it a bit more clear that this is >>> actually an infinite loop that can be escaped only when certain criteria >>> are met. Doesn't really make a difference, though, I don't think. >> >> Sorry, I forgot to mention that you have a slight duplication of logic, >> because you've written 'while count < 3' and 'if count == 3'. This >> means if Granny turns on her hearing aid you have to remember to change >> the 3 in two places in code. (Look up the DRY principle.) >> >> To get around this you should consolidate that logic, and I can think of >> two simple ways: >> >> 1) what I said above, with a 'loop{}' and 'break' structure, or >> 2) remove the final 'if-end' block and move the puts statement to the >> bottom of the code, after the while loop: >> >> count=0 >> while count < 3 >> response=gets.chomp >> if 'BYE' == response >> count+=1 >> elsif response == response.upcase >> puts "NO, NOT SINCE "#{rand(21)+1930}" >> count=0 >> else >> puts "HUH?! SPEAK UP SONNY!" >> count=0 >> end >> end >> puts "OK. Fine. Just leave then." >> >> Even more like @steve_k61's code, huh? > > > It really is...Thanks for the pointers. I haven't learned loop do yet, > so looking forward to that one. I guess the final conditional statement > was really unnecessary since the while loop would keep going until > count==3. Thanks again. > > -- > Posted via http://www.ruby-forum.com/. > Since we're sharing, here's mine: puts "HI, SONNY!\nIT'S YOUR GRANDMA." byes=0 begin print "> " reply = gets.chomp if reply == 'BYE' byes += 1 case byes when 1; puts "CAN'T HEAR YOU, DEAR!" when 2; puts "STILL CAN'T HEAR YOU, SONNY!" else ; puts "OKAY, BYE!" end else byes = 0 if reply == reply.upcase puts "NO, NOT SINCE #{rand(21)+1930}!" else puts "EHH?? WHAT\'S THAT??" end end end until byes >= 3 Outputs: HI, SONNY! IT'S YOUR GRANDMA. > hi gramma EHH?? WHAT'S THAT?? > HI GRAMMA! NO, NOT SINCE 1939! > HOW'S GRAMPA? NO, NOT SINCE 1934! > bye EHH?? WHAT'S THAT?? > BYE CAN'T HEAR YOU, DEAR! > really?? EHH?? WHAT'S THAT?? > BYE CAN'T HEAR YOU, DEAR! > BYE STILL CAN'T HEAR YOU, SONNY! > BYE OKAY, BYE!