The Top Level Context
In this chapter we will discuss about the top level context in Ruby program. We will experiment sending messages with and without explicit receiver.
Top Level
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.
puts 'hello'
As you would expect, this prints:
hello
The IO Class
Can we use an explicit receiver? Let's ask Ruby for the public instance methods of IO class.
puts IO.public_instance_methods(false).grep(/put/)
The grep searches for methods that has put in its name. The result shows that the puts is a public instance method of IO class.
putc
puts
The false argument to the method filters out the methods from the super-class of IO class.
Hello with Receiver
The puts is an instance method in IO class. Let's call the public instance method puts in the IO class.
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.puts 'hello'
Here the $stdout is the Ruby built-in global variable for standard output. Global variables can be accessed from anywhere.
Summary
In this chapter 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 chapter, we will see what happens when we call puts without an explicit receiver.