开发者

Setting end-of-line character for puts

开发者 https://www.devze.com 2022-12-30 10:35 出处:网络
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:

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

UPDATE 1

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> prin开发者_如何学Ct a
123
=> nil
irb(main):004:0> puts a
1
2
3
=> 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?


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
0

精彩评论

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