How do I read an input file and print it back to STDOUT
exactly as the original file. This should be very simple
but the output of my program is all garbled.
What am I doing wrong?
( I am using http://www.rubycentral.com/book to learn Ruby)
How do I read an input file and print it back to STDOUT
exactly as the original file. This should be very simple
but the output of my program is all garbled.
What am I doing wrong?
( I am using http://www.rubycentral.com/book to learn Ruby)
If you do have occasion to loop through an array of lines (which no
doubt you will at some point), remember that chop doesn't do a
permanent chop. What you probably want is chomp!, which removes a
trailing newline if there is one.
David
···
On Thu, 25 Dec 2008, joemacbusiness@gmail.com wrote:
------------------------------------------------------------------------
Reads the entire file specified by _name_ as individual lines, and
returns those lines in an array. Lines are separated by
_sep_string_.
a = IO.readlines("testfile")
a[0] #=> "This is line one\n"
So, the problem is that the 'r' is not the file input mode, but the
separator character! The fact you had the words "car", "bar" and "paper"
(all ending in 'r') made this rather unclear. It looks like it's mostly
splitting at the end of a line, but actually it's splitting after a
letter 'r'.
I wanted to loop through the input file "line-by-line"
and print it out the same way. Sorry I did not make that
clear.
Here is the code block that does what I wanted.
inputFile = File.open("input4", 'r')
while line = inputFile.gets()
puts line
end
Thank you, --JM
···
On Dec 24, 9:26 am, "David A. Black" <dbl...@rubypal.com> wrote:
Hi --
On Thu, 25 Dec 2008, joemacbusin...@gmail.com wrote:
> Hi All,
> How do I read an input file and print it back to STDOUT
> exactly as the original file. This should be very simple
> but the output of my program is all garbled.
> What am I doing wrong?
> ( I am usinghttp://www.rubycentral.com/bookto learn Ruby)
> The program, input, and runtime output are below.
If you do have occasion to loop through an array of lines (which no
doubt you will at some point), remember that chop doesn't do a
permanent chop. What you probably want is chomp!, which removes a
trailing newline if there is one.