Ruby Basics : The Top Level Context
In this article we will discuss about the top level context in Ruby program. We will experiment sending messages with and without explicit receiver.
What is top level? You are in top level when you have not entered into a class, module or method definition. Or exited from all class, module or method definitions.
Hello without Receiver
Let's write a simple program that prints hello at the top level.
As you would expect, this prints:
The IO Class
Can we use an explicit receiver? Let's ask Ruby for the public instance methods of IO class.
grep searches for methods that has
put in its name. The result shows that the
puts is a public instance method of IO class.
The false argument to the method filters out the methods from the super-class of IO class.
Hello with Receiver
puts is an instance method in IO class. Let's call the public instance method
puts in the
io = IO.new(1) io.puts 'hello'
The argument to IO constructor, 1, tells Ruby to print to the standard output. This prints
hello to the terminal.
Standard Output Global Variable
It's the same as doing:
$stdout is the Ruby built-in global variable for standard output. Global variables can be accessed from anywhere.
In this article we discussed about the top level context in Ruby program. We called the puts method using an explicit receiver as well as without providing an explicit receiver. In The Default Receiver article, we will see what happens when we call puts without an explicit receiver.