如何在Ruby中使用stdin和stdout

问题描述 投票:-1回答:1

因此,我有一个下面的方法可以使用,而无需使用stdin或stdout。

def main(lines)
  lines.each_index do |i|
    word = lines[i]
    if word.length > 1 && word.length <=11 
    puts "I use #{word}"
  end
  end
end

main(["Google", "yahoo", "stackoverflow", "reddit"])

但是我试图了解stdin和stdout如何与上述功能一起使用。

因此,当标准输入为“ Google”时,标准输出为“我使用Google”

为了使它工作,我不得不用上述数组替换main(readlines)

main(readlines) ===> main(["Google", "yahoo", "stackoverflow", "reddit"])

我不知道如何执行此操作的命令行。

对于标准输出,会在puts之前出现吗?

stdout.puts "I use #{word}"
ruby stdout stdin
1个回答
1
投票

使用以下方法之一:

$stdout.puts "I use #{word}"

STDOUT.puts "I use #{word}"

有关更多信息,请参见“ Difference between $stdout and STDOUT in Ruby”。

您可以使脚本更简单:

def main(lines)
  lines.each_with_index do |i,v| # or use each instead if u just want only the value and change |i,word| to |word|
    if word.length > 1 && word.length <=11 
    puts "I use #{word}"
  end
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.