Understanding how ruby method $stdout works
$stdout
is a global variable. By default it stores an object of type IO
associated with the standard output of the program (which is, by default, the console).
puts
is a method of the Kernel
module that actually calls $stdout.send()
and pass it the list of arguments it receives. As the documentation explains, puts(obj, ...)
is equivalent to $stdout.puts(obj, ...)
.
Your code replaces $stdout
with an object of type File
that extends class IO
. When it is created, your object opens the file out.txt
for writing and together with its inheritance from IO
it is fully compatible with the default behaviour of $stdout
.
Since by default, all the output goes to $stdout
, your new definition of $stdout
ensures the output is written to the file out.txt
without other changes in the code.
Difference between $stdout and STDOUT in Ruby
$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.
Getting output of system() calls in Ruby
I'd like to expand & clarify chaos's answer a bit.
If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:
output = `ls`
p output
or
printf output # escapes newline chars
What is the differences between print and puts in Ruby with example?
irb(main):014:0> class Person
irb(main):015:1> attr_accessor :name, :age, :gender
irb(main):016:1> end
=> nil
irb(main):017:0> person = Person.new
=> #<Person:0x2bf03e0>
irb(main):018:0> person.name = "Robert"
=> "Robert"
irb(main):019:0> person.age = 52
=> 52
irb(main):020:0> person.gender = "male"
=> "male"
irb(main):021:0> puts person
#<Person:0x2bf03e0>
=> nil
irb(main):022:0> print person
#<Person:0x2bf03e0>=> nil
irb(main):023:0> print person.name
Robert=> nil
irb(main):024:0> puts person.name
Robert
=> nil
The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.
puts isn't prefixed by the name of a class or object upon which to complete the method and puts is a method made available from the Kernel module and that is included and searched by default, so usually you won’t need to use Kernel.puts to refer to it.
Kernel.puts "Hello, world!"
puts takes only one argument and is rarely followed by other methods or logic, so parentheses are not strictly necessary.
Difference between ways to use gets method
"Flushing" the output ensures that it shows the printed message before it waits for your input; this may be just someone being certain unnecessarily, or it may be that on certain operating systems you need it. Alternatively you can use STDOUT.sync = true
to force a flush after every output. (You may wonder, "Why wouldn't I always use this?" Well, if your code is outputting a lot of content, repeatedly flushing it may slow it down.)
chomp
removes the newline from the end of the input. If you want the newline (the result of the user pressing "Enter" after typing their name) then don't chomp
it.
What is Ruby's equivalent of Python's sys.executable?
Run this in IRB:
require 'rbconfig'
key_length = RbConfig::CONFIG.keys.max{ |a,b| a.length <=> b.length }.length
RbConfig::CONFIG.keys.sort_by{ |a| a.downcase }.each { |k| puts "%*s => %s" % [key_length, k, RbConfig::CONFIG[k]] }
It will output an "awesome print" style list of all the Ruby configuration info.
ALLOCA =>
AR => ar
arch => x86_64-darwin10.5.0
ARCH_FLAG =>
archdir => /Users/greg/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/x86_64-darwin10.5.0
ARCHFILE =>
AS => as
ASFLAGS =>
BASERUBY => ruby
bindir => /Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin
bindir
is the path to the currently running Ruby interpreter. Above it in the list is BASERUBY => ruby
.
RbConfig::CONFIG.values_at('bindir', 'BASERUBY').join('/')
=> "/Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/ruby"
Checking my work:
greg-mbp-wireless:~ greg$ which ruby
/Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
There's a lot more information than this so it's worth running the code I added above to see what's available.
Related Topics
Fast Way of Counting Non-Zero Bits in Positive Integer
Pyqt Showing Video Stream from Opencv
Pandas: Replace Substring in String
How to Serve Multiple Clients Using Just Flask App.Run() as Standalone
How to Pull Out CSS Attributes from Inline Styles with Beautifulsoup
How to Add Sum to Zero Constraint to Glm in Python
Numpy/Scipy Equivalent of R Ecdf(X)(X) Function
Pyobjc VS Rubycocoa for MAC Development: Which Is More Mature
Simple File Server to Serve Current Directory
Create Dynamic Urls in Flask with Url_For()
How to Exchange Keys with Values in a Dictionary
Multiprocessing Example Giving Attributeerror
Does Python Optimize Modules When They Are Imported Multiple Times
How to Implement a Tree in Python
Django, Creating a Custom 500/404 Error Page
How to Parse a Time String Containing Milliseconds in It with Python