开发者

Reading from stdin and printing to stdout in Ruby

This question is kinda simple (don't be so harsh with me), but I can't get a code-beautiful solution. I have the following code:

ARGF.each_line do |line|
  arguments = line.split(',')
    arguments.each do |task|
    puts 开发者_如何学JAVA"#{task} result"
  end
end

It simply read from the standard input numbers. I use it this way:

echo "1,2,3" | ruby prog.rb

The output desired is

1 result
2 result
3 result

But the actual output is

1 result
2 result
3
 result

It seems like there's a newline character introduced. I'm skipping something?


Each line ends in a newline character, so splitting on commas in your example means that the last token is 3\n. Printing this prints 3 and then a newline.

Try using

arguments = line.chomp.split(',')

To remove the trailing newlines before splitting.


Your stdin input includes a trailing newline character. Try calling line.chomp! as the first instruction in your each_line block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜