Question about "gets" in ruby [duplicate]
Asked Answered
T

2

5

I was wondering why when I'm trying to gets to different inputs that 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's 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 ignored my while statement.

This is a sample output.

Hello World!

What is the dog's new name? bob

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

OK...
Torso answered 14/3, 2011 at 20:24 Comment(1)
For hints on how to debug your script, see https://mcmap.net/q/142614/-how-to-debug-ruby-scripts-closedCommorancy
S
17

The problem is you are getting a newline character on your input from the user. while they are entering "y" you are actually getting "y\n". You need to chomp the newline off using the "chomp" method on string to get it to work as you intend. something like:

speak_or_no = gets
speak_or_no.chomp!
while speak_or_no == "y"
  #.....
end
Surprisal answered 14/3, 2011 at 20:30 Comment(1)
Example: rubylearning.com/satishtalim/getting_input.htmlArnst
S
-1

once you use gets()... print that string.. using p(str) usually string will have \n at the end.. chomp! method should be used to remove it...

Sulphanilamide answered 14/5, 2013 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.