开发者

Please explain ruby ARGF behaviour

开发者 https://www.devze.com 2023-02-07 02:07 出处:网络
ARGF.each_with_index do |line, idx| print( \"[#{idx}] #{line} x: \" ); indent = Indent # do stuff indent = \"\"
   ARGF.each_with_index do |line, idx|
      print( "[#{idx}] #{line} x: " );
      indent = Indent
         # do stuff
      indent = ""
   end #ARGF e

Each line from STDIN is displayed as,

   x: [1] W:\sandbox\tmp\for_each\for_each.rake

Which is not good / odd, if you开发者_如何转开发 ask me.

One further unexplained result, the line ...

 print( "ab: [#{idx}] #{line} x: " );

Displays:

x: ab: [1] W:\sandbox\tmp\for_each\for_each.rake

I just get weird feelings here. Three questions, is this a:

  1. HOW does the "x:" string wind-up at the beginning of each 'line' the string??!
  2. Ruby v1.8.7 bug or my bug?
  3. How to fix it?

Help wanted. I keep looking at this and wonder if I what really dumb thing I did? Many thanks in advance.

aloha, Will


each_line does not remove the newlines at the end of the lines, so the strings yielded by each_line will contain newlines. print on the other hand will not add newlines to the end of strings (if you want that, use puts). So print "hello\nworld: followed by print "lala", will print

hello
world:lala

which explains why your output looks the way it does.

To get the output you want, use line.chomp instead of line, which will remove the newline at the end of line and thus prevent your strings from containing a line break before x:.


A small sorry here. I fergot about end of line and CR/LF issues on Windows. The solution seems to be:

line.chomp!
print( "ab: [#{idx}] #{line}:x\n" );

Which prints the line:

ab: [1] W:\sandbox\tmp\for_each\for_each.rake x:

The remaining trap for young players, is to put your own newline(\n) after the chomp!() method. One mistake I made with this was thinking 'trim()' not 'chomp()' -- How crazy are I.

Cheers,

Will

0

精彩评论

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

关注公众号