Ruby gets()没有返回正确的字符串 [英] Ruby gets() not returning correct string
问题描述
我决定在听到所有关于它的所有好事之后给Ruby一个机会,但到目前为止它只给了我一个艰难的时间。很久以前我在学习Python时创建了一个搜索引擎,它只是将数据存储在数组中并检查搜索关键字是否在其中,我一直在尝试在Ruby中做同样的事情。
I decided to give Ruby a go today after hearing all of the great things about it, but so far it has only been giving me a hard time. A long time ago I made a "search engine" while learning Python that just stores data in an array and checks if the search keyword is in it, and I've been trying to do the same thing in Ruby.
虽然它不像Python那样直观,但我的搜索功能正常运行。但是,我在处理用户输入时遇到了麻烦。我想检查输入是否等于插入,搜索和退出,但它只是不起作用。我真的不知道如何使用获取,所以我假设问题与获取相关。
Although it wasn't as intuitive as it was in Python, I got the search functionality working. I'm having trouble working with user input, though. I want to check if the input equals insert, search, and quit, but it just doesn't work. I don't really know how to use gets, so I'm assuming the issue is gets-related.
while true
puts 'What do you want to do?'
choice = $stdin.gets
puts choice # => quit
if choice == 'quit'
break
end
end
if 语句不起作用。我到底做错了什么?为了上帝的缘故,这在 C ++ 中是微不足道的!
The if statement doesn't work. What the heck am I doing wrong? This is trivial in C++ for God's sake!
我真的很感激一些帮助。 Ruby对我来说太陌生了...谢谢!
I would really appreciate some help. Ruby is so foreign to me... thanks!
推荐答案
我认为获取包括输入结尾的换行符。尝试使用 gets.chomp
而不是
I think the gets includes the newline at the end of the input. try using gets.chomp
instead
irb(main):001:0> input = $stdin.gets
hello
=> "hello\n"
irb(main):002:0> input = $stdin.gets.chomp
hello
=> "hello"
这篇关于Ruby gets()没有返回正确的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!