Why Ruby can be scripting language?
Before I start writing Ruby, my main language is Java. The most verbose thing in Java world is everything should be defined in classes. You need to have a class and a static main function even you just want to print a
hello world. You can’t directly write or call a function globally with Java, that’s why Java can’t become a scripting language. If you have Ruby in hand, the only thing need to do is leave a line
puts 'hello world'. I think the top level function definition and invocation is the most important reason why Ruby can be a perfect scripting language.
Isn’t Ruby pure OO?
All Rubists know Ruby is a pure object-oriented language. So how the top level functions come? Everything in Ruby even a integer or a char is a object, and there is no function, only method defined for class. So what’s the receiver for the
puts method above.
There is a
self object refers to the current object in any scope1. Method call without explicit receiver is sent to
self. So the receiver of the
puts method above is
self, you can inspect it by
p self. It will print a
main for you, which is is the default top object.
There is a top object called
main at the top level, and
main is the current object for everything invoked at top level. And more, as a scripting language, Ruby can define function globally. Now we know this function actually is method, but what’s the owner of this method?
def global_method puts "this method can be called everywhere" end
We find the owner like this:
You can see the owner of method
Object. That’s why you can call this method in every place, all classes in Ruby are inherited from
Object, so every object has the method
global_method. But you just can invoke this method without explicit receiver or using
send, because it’s private method.
But here has a question not apparent, why this method defined for class
Object? We know that the
def keyword in Ruby is to define instance method for current class2. If the
def appears in class definition, it’s obvious that the current class is the class defined, but here the method is global, is not in any class definition. What’s the current class for globally defined methods? Intuitively, the current class should be the singleton class of
main, but here is a exception, the global
def works on
Object. The code from Rubinius proves this point.
class << MAIN def define_method(*args, &block) Rubinius.privately do Object.define_method(*args, &block) end end end
Same reason can apply on
include. The modules included globally are mixed into
Object. The methods mixed in are all available at top level and within any object.
module M1 def method1 puts "this method in module will be mixed to everywhere" end end include M1 method1 Object.new.method1
Of course Ruby is a scripting language, and also a object-oriented language, but Ruby adopts a smart method to implement the convenient way to write commands as scripts, in which the core is exactly the top level of Ruby.