The question of β€œgets” in ruby

I was wondering why, when I try to get different inputs, it ignores the second input that I had.

#!/usr/bin/env ruby
#-----Class Definitions----

class Animal
  attr_accessor :type, :weight
end

class Dog < Animal
  attr_accessor :name
  def speak
    puts "Woof!"
  end
end

#-------------------------------

puts
puts "Hello World!"
puts

new_dog = Dog.new

print "What is the dog new name? "
name = gets
puts

print "Would you like #{name} to speak? (y or n) "
speak_or_no = gets

while speak_or_no == 'y'
  puts
  puts new_dog.speak
  puts
  puts "Would you like #{name} to speak again? (y or n) "
  speak_or_no = gets
end

puts
puts "OK..."

gets

As you can see, it completely ignores my while statement.

This is an example output.

Hello World!

What is the dog new name? bob

Would you like bob
 to speak? (y or n) y

OK...
+5
source share
2 answers

The problem is that you get a newline at your input from the user. while they enter "y", you actually get "y \ n". You need to compress the new line using the "chomp" method in the line to make it work the way you plan. sort of:

speak_or_no = gets
speak_or_no.chomp!
while speak_or_no == "y"
  #.....
end
+16
source

gets()... .. p (str) \n .. chomp! ...

-1

All Articles