Ruby stdio consts and globals, what are the benefits?

Ruby has constants and global variables for stdio.

Namely, consts STDIN, STDOUT, STDERRand their variables, $stdin, $stdout, $stderr.

I understand the difference between constant and variable. I know that constants are invariably set to file descriptors at the moment the script was exec'd.

I also understand that you can change (some) variables at runtime.

I am curious about the practical use of such a function. Why would you do this? What can you achieve?

Seeing sample code or even just used cases extracted from real-world projects would be great.


Update . From what I am collecting so far, it seems that when writing your own libraries / programs, you should use variables over constants so that its users can deal with it, Right?

+3
source share
4 answers

A more efficient version of this function is used in production code:

#!/usr/bin/env ruby -rstringio

def capture_stdout
  $stdout = StringIO.new
  begin
    yield
    $stdout.string
  ensure
    $stdout = STDOUT
  end
end

output = capture_stdout do
  print "Line"
  puts " 1"
end

p output     # => "Line 1\n"

It is used in unit tests that want to know what was written on the console using printor puts.

Variables $allow Ruby to provide various I / O objects for stdout, stdin, stderr:

$stdout = buffer

$ ( ) :

$stdout = STDOUT
+3

, , . 9.7.1.4 : " , print puts, $stdout. script , ".

, , , , .

+2
$stderr = File.open 'error.log', 'w'

error.log

+1

, , .

0

Source: https://habr.com/ru/post/1727045/


All Articles