问题
I'm trying to get simple user input in Ruby, but I can't get it working. I'm using the gets
method, but the program never stops to ask me for input. I'm using Sublime Text 2 as my text editor, and I run the program in it, too (if this makes a difference).
Here's my code:
puts "What is your name?"
name = gets
puts "Hello " + name + ". How are you?"
And here's the error (and output) given to me:
C:/Users/Sten Sootla/Desktop/Ruby workspace/exercise.rb:3:in `+': can't convert nil into String (TypeError) from C:/Users/Sten Sootla/Desktop/Ruby workspace/exercise.rb:3:in `' What is your name? [Finished in 0.1s with exit code 1]
Why doesn't the program stop to ask me for input?
回答1:
Here's how I understand it. gets
and puts
are instance methods of IO
, and the default IO
s are $stdout
and $stdin
.
Calls to gets/puts will only be effective if the translator is capable of handling stdout/in e.g. IRB
If you run a ruby file from bash it works too.
io_test.rb
puts gets
in bash
ruby io_test.rb
Then it will "put" into stdout whatever it "gets" from stdin.
回答2:
Try using $stdin.gets
instead of just a plain gets
, this will force the input to come from stdin
回答3:
If you want to run code within ST2, check out the SublimeREPL plugin, available through Package Control. While you can use IRB
, its main Ruby interface is through pry, which is a lot more powerful. You can use it as a classic REPL (think Clojure or LISP), and you can also transfer your code from one tab into the running REPL in another tab by selection, line range, or block.
Interestingly, your code above works in IRB
for me, but not pry
for some reason - it's reading my $EDITOR
environment variable, which is set to subl -w
but failing with Errno::ENOENT: No such file or directory - subl -w
. Strange...
At any rate, I highly highly recommend SublimeREPL, as it's a really powerful tool, and is self-contained within ST2, so you don't have to keep flipping back and forth to your terminal, saving and reloading your programs.
来源:https://stackoverflow.com/questions/17377864/ruby-gets-doesnt-work