user1934428
user1934428

Reputation: 22217

Ruby: Setting output separator for IO object

(Crossposting note: This question has already been asked at https://www.ruby-forum.com/topic/6879239 without getting a response)

From the documentation of IO#print:

"Writes the given object(s) to ios. ... If the output record separator ($\) is not nil, it will be appended to the output."

If I take this literally, it means that I can only have a single output separator ($\) for all streams. But in general, I have several streams open for writing. How can I set different output separators for them?

Upvotes: 0

Views: 92

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Yes, there is one global record separator and you can't set it per-stream.

Upvotes: 1

garbo999
garbo999

Reputation: 393

I have been reading about Procs and here is an idea (perhaps far-fetched). Could you package the different values of $\ that you need into Procs (which maintain their creation context)? You could do your stream processing inside the block belonging to the Proc.

def stream_1_proc
  $\ = <value1>
  return Proc.new { puts $\ }
end

def stream_2_proc
  $\ = <value2>
  return Proc.new { puts $\ }
end

# it seems like this should NOT work because $\ is global,
# but it works for me in IRB
stream_1_proc.call # $\ = <value1>
stream_2_proc.call # $\ = <value2>

That solution is not DRY, but maybe instead you could pass an argument to a single function with the value for $\ (but would $\ get overwritten between calls?).

def stream_proc(output_separator)
  $\ = output_separator
  return Proc.new { puts $\ }
end

Upvotes: 0

Related Questions