In Java, every function must be wrapped by a class, but in Ruby, we can define a function without classes. Therefore, some years ago I used to suppose that:
There are no functions in Java, only methods. But for Ruby, we can have a function that isn't a method.
However, these days I have realized that: "Every function in Ruby is also a method".
But why can we define the function at the top-level scope, without creating classes for them, like Java? Or which class does this function belong to?
For example, I have the function increment
def increment(num)
num + 1
end
We try to call increment
this way:
self.increment 10
# or
self.send(:increment, 10)
Since self
keyword contains a reference to the current object, the receiver for the current method, increment
must be a method. Now let's check which object self
reference to.
puts self
# => main
puts self.class
# => Object
You can see puts self
code returns string "main", and it is an instance of Object
, the root class of Ruby’s class hierarchy. So we can conclude that increment
is an instance method in the Object
class.
Technically speaking, Ruby automatically creates a main
object as the top self object, it is the default receiver for top-level methods. Actually, all Ruby functions are private methods of Object
.
p Object.private_instance_methods
# [:increment, :DelegateClass, :sprintf, ...]
Conclusion
- Every function in Ruby is also a method. It's an instance method of
Object
class. - Ruby
main
object allows you to write simple functions and, at the same time, ensure sophisticated OO design.