Take the 2-minute tour ×

I have an array of entries I would like to print.

Being arr the array, I used just to write:

puts arr

Then I needed to use the DOS format end-of-line: \r\n, so I wrote:

arr.each { |e| print "#{e}\r\n" }

This works correctly, but I would like to know if there is a way to specify what end-of-line format to use so that I could write something like:

$eol = "\r\n"
puts arr


I know that puts will use the correct line-endings depending on the platform it is run on, but I need this because I will write the output to a file.

UPDATE 2 As Mark suggested, setting $\ is useful. Anyway it just works for print. For example,

irb(main):001:0> a = [1, 2, 3]
=> [1, 2, 3]
irb(main):002:0> $\ = "\r\n"
=> "\r\n"
irb(main):003:0> print a
=> nil
irb(main):004:0> puts a
=> nil

print prints all array items on a single line and then add $\, while I would like the behaviour of puts: adding $\ after each item of the array.
Is this possible at all without using Array#each?

share|improve this question
Doesn't puts add a carriage return depending on the platform ? Could you tell us what output you get and what output you want ? –  philant May 18 '10 at 10:18
@philippe: Yes I know but I will write the output to a text file that I want to be stored with CR/LF line endings –  Dom De Felice May 18 '10 at 10:28
add comment

1 Answer

up vote 4 down vote accepted

The Ruby variable $\ will set the record separator for calls to print and write:

>> $\ = '!!!'
=> "!!!"
>> print 'hi'
hi!!!=> nil

Alternatively you can refer to $\ as $OUTPUT_RECORD_SEPARATOR if you import the English module.

Kernel#puts is equivalent to STDOUT.puts; and IO.puts "writes a newline after every element that does not already end with a newline sequence". So you're out of luck with pure puts for arrays. However, the $, variable is the separator string output between parameters suck as Kernel#print and Array#join. So if you can handle calling print arr.join, this might be the best solution for what you're doing:

>> [1,2,3].join
=> "123"
>> $, = '---'
=> "---"
>> [1,2,3].join
=> "1---2---3"
>> $\ = '!!!'
=> "!!!"
>> print [1,2,3].join
1---2---3!!!=> nil
share|improve this answer
Nice, but is it possible to do the same with puts? I ask this because doing -- $\ = "\r\n" ; print arr -- prints the array items on a single line while I would like to automatically print each entry on a different line, like puts does –  Dom De Felice May 18 '10 at 10:59
Thanks for your time and your useful answer :-) –  Dom De Felice May 18 '10 at 12:10
add comment

Your Answer


