如何在 Ruby 中结合 gets.chomp 和 ARGV?

Phi*_*pot 4 ruby

我刚开始学习 ruby​​,目前坚持在同一个脚本中使用 ARGV 和 gets.chomp。

我希望脚本首先解压 3 个参数,然后我会问一个问题 (gets.chomp),然后打印包含 ARGV 和 gets.chomp 变量之一的字符串。在终端中,我将 ARGV 设置为一二三(例如:ruby file1.rb 一二三)。下面的代码示例:

first, second, third = ARGV

puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
Run Code Online (Sandbox Code Playgroud)

这完全符合我的预期。在终端中,它给了我一、二和三作为第一、第二和第三个变量。

我在 puts 中添加了“你最喜欢的颜色是什么”,这会按预期打印出来,但是当我为输入设置 gets.chomp 时,出现错误。

first, second, third = ARGV

puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"

puts "What is your favourite colour? "
colour = gets.chomp  #this is where the error occurs

puts "So your favourite number is #{first} and you like the colour #{colour}."    
Run Code Online (Sandbox Code Playgroud)

^底线是我想打印的内容,但在 gets.chomp 中出现错误

这是终端打印的内容:

$ ruby ex13.rb one two three
Your first variable is: one
Your second variable is: two
Your third variable is: three
What is your favourite colour? 
ex13.rb:8:in `gets': No such file or directory - one (Errno::ENOENT)
from ex13.rb:8:in `gets'
from ex13.rb:8:in `<main>'
Run Code Online (Sandbox Code Playgroud)

我希望我已经很好地解释了上述内容,如果需要更多信息,请告诉我。

任何帮助将不胜感激!

谢谢,

max*_*ner 5

我昨天回答了一个关于这个的问题,你可以在这里阅读,但要具体解决你的情况:

之后first, second, third = ARGV,打电话ARGV.clear清空它。

或者你可以做 first, second, third = 3.times.map { ARGV.shift }

原因是gets如果其中有任何内容,则从 ARGV 读取。您需要在调用之前清空 ARGV gets