关于“得到”的问题在红宝石中

发布于 2024-10-22 02:04:09 字数 799 浏览 1 评论 0原文

我想知道为什么当我尝试获取不同的输入时,它会忽略我的第二个输入。

#!/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 语句。

这是一个示例输出。

Hello World!

What is the dog's new name? bob

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

OK...

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮生未歇 2024-10-29 02:04:09

问题是您在用户的输入中收到换行符。当他们输入“y”时,您实际上得到的是“y\n”。您需要使用字符串上的“chomp”方法来截断换行符,以使其按您的预期工作。像这样的东西:

speak_or_no = gets
speak_or_no.chomp!
while speak_or_no == "y"
  #.....
end

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
轻许诺言 2024-10-29 02:04:09

一旦你使用 gets()...
使用 p(str) 打印该字符串..
通常字符串末尾会有 \n .. chomp!应该使用方法将其删除...

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文