Ruby gets() not returning correct string

2019-02-28 06:47发布

问题:

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.

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

The if statement doesn't work. What the heck am I doing wrong? This is trivial in C++ for God's sake!

I would really appreciate some help. Ruby is so foreign to me... thanks!

回答1:

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"


回答2:

davidrac is correct, you need to chop off the \n

Quoting the answer from here

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