Joe Half Face
Joe Half Face

Reputation: 2333

Text file is read incorrectly (partly)

I have myscr file:

#!/usr/bin/env ruby

while $stdin.getc
  puts "char \n"
  puts $stdin.getc
end

puts $stdin.read.inspect

When I execute command:

cat foo.txt | ruby mysrc

I have following output:

char 
o
char 

char 
a
char 

char 
a
char 

""

So as you can see, it doesn't start with first character, also, for some reason the whole string of .read turns to be empty, as well as some characters from .getc, and some are correct

Upvotes: 0

Views: 29

Answers (1)

tadman
tadman

Reputation: 211560

Calling getc twice attempts to fetch two characters. Maybe what you mean is:

while (char = $stdin.getc)
  puts "Char: %s" % char
end

Now any characters you've read are consumed, so you'll need to save them if you want to use those for later input.

Upvotes: 1

Related Questions