If everything is an object in Ruby, to the point that even math operators are methods applied to objects, when I write:
puts "Hello world"
The method is puts, and the parameter is "Hello world", but what is the object?
Everything in Ruby is an object. All objects have an identity; they can also hold state and manifest behaviour by responding to messages. These messages are normally dispatched through method calls. A string is an example of a Ruby object.
Ruby is a pure object-oriented language, which means that in the Ruby language, everything is an object. These objects, regardless of whether they are strings, numbers, classes, modules, etc., operate in a system called The Object Model. Ruby offers a method called the object_id , which is available to all objects.
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. Hello World the program is the most basic and first program when we start a new programming language. This simply prints Hello World on the screen. Below is the program to write hello world”.
This is how Ruby implements object-oriented code in C: a Ruby object is an allocated structure in memory that contains a table of instance variables and information about the class. The class itself is another object (an allocated structure in memory) that contains a table of the methods defined for that class.
To find a method, you could call :
method(:puts)
#=> #<Method: Object(Kernel)#puts>
So puts
is a method defined in Kernel
, available to every Object.
puts "Hello world"
is actually
self.puts( String.new("Hello world") )
Where self
is the object main
.
So puts "hello world"
is a :
main
Note that if you execute
self.puts( String.new("Hello world") )
you'll get an error :
private method `puts' called for main:Object (NoMethodError)
Because every Kernel method is made available to every Object, but as a private method. You'd need :
self.send(:puts, String.new("Hello world") )
Another way to check would be :
module Kernel
def my_puts(*args)
print "Calling Kernel#my_puts on #{self} with #{args}\n"
print "Now delegating to Kernel#puts on #{self} with #{args} :\n"
puts(*args)
end
end
my_puts "Hello world"
It outputs :
Calling Kernel#my_puts on main with ["Hello world"]
Now delegating to Kernel#puts on main with ["Hello world"] :
Hello world
See? Everything is an object, even though it might not look like it.
In the same vein : 2+3
is actually Integer(2).+( Integer(3) )
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With