Difference between $stdout and STDOUT in Ruby

前端 未结 3 802
长发绾君心
长发绾君心 2020-12-02 11:33

In Ruby, what is the difference between $stdout (preceded by a dollar sign) and STDOUT (in all caps)? When doing output redirection, which should b

3条回答
  •  抹茶落季
    2020-12-02 12:12

    • STDOUT is a global constant, so it should not be changed.
    • $stdout is a predefined variable, so it can be changed.

    If you are using the shell to do redirection:

    $ ruby test.rb > test.log
    

    then it doesn't matter which one you use as the file descriptor for your script is being determined before your script is executed.

    However, if you are trying to change the file descriptor for the OS's STDOUT from within your Ruby script, for example to send output to a rotating set of log files based on the current day of the week, then you'll want to make sure you use $stdout.

提交回复
热议问题