how to enter an input to gets function via script in ruby
Whenever gets
is called, is there any way to enter input via script itself, instead of entering manually in windows?
For examp开发者_如何学Gole:
puts "enter your choice"
ch=gets
puts ch
In the above script when gets
is called, is there any command to enter input to that via a script in windows?
Thanks in advance.
The gets
function simply reads from $stdin
so all you have to do is open a new File
or StringIO
for reading and then assign it to $stdin
.
For example, if you have a file called pancakes.txt
and you do this:
$stdin = File.new('pancakes.txt', 'r')
puts gets
Then you'll see the first line of pancakes.txt
on the standard output.
1) If you want to provide external input to STDIN when invoking your script
Let's say your gets command is inside a file named prog.rb. If you'd like to provide some fixed input to STDIN when running prog.rb, you could run it using a pipe from the command line:
echo "My input to gets" | ruby prog.rb
This will output
enter your choice
My input to gets
in the shell without requiring manual intervention.
2) An example for feeding STDIN from within the same script:
class MyIO
def gets
"1\n"
end
end
$stdin = MyIO.new
puts "enter your choice"
ch=gets
puts ch # => 1
精彩评论