本文介绍了有关“获取"的问题在红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道为什么当我尝试使用其他输入时,它忽略了我的第二个输入.
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
如您所见,它完全忽略了我的while语句.
As you can see it completely ignored my while statement.
这是示例输出.
Hello World!
What is the dog's new name? bob
Would you like bob
to speak? (y or n) y
OK...
推荐答案
问题是您正在从用户的输入中获取换行符.当他们输入"y"时,您实际上得到的是"y \ n".您需要在字符串上使用"chomp"方法来删除换行符,以使其按预期工作.像这样:
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
这篇关于有关“获取"的问题在红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!