Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $stdout and STDOUT in Ruby

In Ruby, what is the difference between $stdout (preceded by a dollar sign) and STDOUT (in all caps)? When doing output redirection, which should be used and why? The same goes for $stderr and STDERR.

Edit: Just found a related question.

like image 524
jrdioko Avatar asked Jul 12 '11 21:07

jrdioko


People also ask

What is stdout in Ruby?

The $stdout is a global variable which holds the standard output stream. printing2.rb. #!/usr/bin/ruby $stdout.print "Ruby language\n" $stdout.puts "Python language" We print two lines using the $stdout variable. Ruby has another three methods for printing output.

What's the difference between stdout and stderr?

stdout − It stands for standard output, and is used to text output of any command you type in the terminal, and then that output is stored in the stdout stream. stderr − It stands for standard error. It is invoked whenever a command faces an error, then that error message gets stored in this data stream.


2 Answers

$stdout is a global variable that represents the current standard output. STDOUT is a constant representing standard output and is typically the default value of $stdout.

With STDOUT being a constant, you shouldn't re-define it, however, you can re-define $stdout without errors/warnings (re-defining STDOUT will raise a warning). for example, you can do:

$stdout = STDERR 

Same goes for $stderr and STDERR


So, to answer the other part of your question, use the global variables to redirect output, not the constants. Just be careful to change it back further on in your code, re-defining global variables can impact other parts of your application.

like image 108
Brian Avatar answered Sep 19 '22 06:09

Brian


Both $stdout and STDOUT have different meanings. Ruby's documentation is pretty clear on this topic:

  • $stdout – The current standard output.
  • STDOUT – The standard output. The default value for $stdout.

When you want to write to the standard output, then you actually mean the current standard output, thus you should write to $stdout.

STDOUT isn't useless too. It stores the default value for $stdout. If you ever reassign $stdout, then you can restore it to the previous value with $stdout = STDOUT.

Furthermore, there's one more predefined variable:

  • $> – The default output for print, printf, which is $stdout by default.

However it looks like in Ruby 2.3 it simply behaves as an alias for $stdout. Reassigning $stdout changes the value of $> and vice versa.

like image 28
skalee Avatar answered Sep 22 '22 06:09

skalee