0

I'm trying to get out of a while loop when the input is this:

BYE
BYE
BYE

And not this:

BYE BYE BYE

The code is:

my_reply = ((word1 = gets) + (word2 = gets) + (word3 = gets))

while my_reply != ((word1 == 'BYE') and (word2 == 'BYE') and (word3 == 'BYE'))
    puts 'Grandma: ...'
    my_reply = ((word1 = gets) + (word2 = gets) + (word3 = gets))
end

puts 'Grandma: ' + 'Fine, sonny, don\'t hang out with your aging grandmother!'.upcase

which is not working. I need help.

sawa
  • 165,429
  • 45
  • 277
  • 381
wulymammoth
  • 8,121
  • 4
  • 19
  • 19

3 Answers3

1

gets also returns the line feed and carriage return "\r\n", e.g. "BYE\r\n". This means you have to strip them out before comparing to other strings. (see String.strip)

while [gets, gets, gets].map(&:strip) != ['BYE', 'BYE', 'BYE']
  puts 'Grandma: ...'
end

puts 'Grandma: ' + 'Fine, sonny, don\'t hang out with your aging grandmother!'.upcase
Matt
  • 17,290
  • 7
  • 57
  • 71
0

The input from gets includes a newline (BYE\n). Do gets.chomp to get rid of it.

steenslag
  • 79,051
  • 16
  • 138
  • 171
0

I am not quite sure, but may be you are trying to do something like:

bye_3 = Array.new(3, "BYE")
until Array.new(3){gets.chomp} == bye_3
  puts "Grandma: ..."
end
puts 'Grandma: ' + 'Fine, sonny, don\'t hang out with your aging grandmother!'.upcase

Array.new(3, "BYE") is the same as ["BYE", "BYE", "BYE"], and Array.new(3){gets.chomp} is the same as [gets.chomp, gets.chomp, gets.chomp].

sawa
  • 165,429
  • 45
  • 277
  • 381