2016-11-13 98 views
2

我是学习ruby的新手,目前坚持在同一个脚本中使用ARGV和gets.chomp。如何在Ruby中结合gets.chomp和ARGV?

我希望脚本先解压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}" 

这种方式完全如我所料。在终端中,它给了我1,2和3个变量,分别是第一,第二和第三。

我在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}."  

^底线是我想打印什么,但我在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>' 

我希望我已经解释上面已经足够了,让我知道是否需要更多信息。

任何帮助将不胜感激!

感谢,

+0

你会得到什么错误? – spickermann

+0

@spickermann 你最喜欢什么颜色? ex13.rb:8:'得到 ':没有这样的文件或目录 - 一个(错误:: ENOENT)从ex13.rb \t:8:'得到' 从ex13.rb \t:8:'

' 我现在会用终端错误更新我的问题。 – Philpot

回答

2

我回答这个昨天,你可以阅读here,而是专门针对您的情况的问题:

first, second, third = ARGV

后,调用ARGV.clear空出来。

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

的原因是,从gets ARGV读取,如果有一个在任何事情。在致电gets之前,您需要清空ARGV。

+0

'STDIN.gets.chomp'也有效,但我无法解释为什么? –

+0

请参阅[红宝石之间的差异stdin-gets-and-gets-chomp](http://stackoverflow.com/questions/12041492/ruby-whats-the-difference-between-stdin-gets-和获得-格格) –