每当调用gets
时,有没有办法通过脚本本身输入输入,而不是在Windows中手动输入?
例如:
puts "enter your choice"
ch=gets
puts ch
在上面的脚本中调用gets
时,有没有命令通过windows中的脚本输入输入?
提前致谢。
答案 0 :(得分:1)
1)如果要在调用脚本时向STDIN提供外部输入
假设您的gets命令位于名为prog.rb的文件中。如果您想在运行prog.rb时向STDIN提供一些固定输入,可以使用命令行中的管道运行它:
echo "My input to gets" | ruby prog.rb
这将输出
enter your choice
My input to gets
在shell中,无需人工干预。
2)从同一个脚本中提供STDIN的示例:
class MyIO
def gets
"1\n"
end
end
$stdin = MyIO.new
puts "enter your choice"
ch=gets
puts ch # => 1
答案 1 :(得分:1)