Ruby gets() not returning correct string

2019-02-28 06:21发布

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!

2条回答
太酷不给撩
2楼-- · 2019-02-28 06:46

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"
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-28 06:48

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

查看更多
登录 后发表回答