junky
junky

Reputation: 1478

How can I get line feeds in Ruby when writing out to a file:

My input file is:

1  
3  
5  
7  
9  

I want my output file to be squares, one per line:

1  
9  
25  
49  
81  

But I am getting:

19254981

i.e. no linespaces

My code is:

a= File.open('inputs')
b= File.open('outputs', 'w')
a.each_line do |one_num|
  one_number = one_num.to_i
  square= one_number * one_number
  b << square
end

Upvotes: 1

Views: 218

Answers (1)

Mark Reed
Mark Reed

Reputation: 95242

use puts instead of <<.

 b.puts square

Side note: you can do the whole thing as one long method chain:

File.open('outputs','w').puts(File.open('inputs').readlines.map{ |l| n=l.to_i; n*n })

Or somewhat more readably as nested blocks:

File.open('outputs','w') do |out|
  File.open('inputs') do |in|
    out.puts( in.readlines.map { |l| n=l.to_i; n*n } )
  end
end

Both of those solutions have the advantage of not leaving any dangling file handles despite the lack of explicit close statements.

Upvotes: 2

Related Questions