Explain how (almost) everything is an object in Ruby:

Explain how (almost) everything is an object in Ruby:



Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.

Take a code block for example:

def what_is(&block)
puts block.class
puts block.is_a? Object
end

> what_is {}
Proc
true
=> nil
Or for a Method:

class A
def i_am_method
"Call me sometime..."
end
end

> m = A.new.method(:i_am_method)
> m.class
Method
> m.is_a? Object
true
> m.call
"Call me sometime..."
And operators (like +, -, [], <<) are implemented as methods:

class String
def +
"I'm just a method!"
end
end
For people coming into programming for the first time, what this means in a practical sense is that all the rules that you can apply to one kind of Object can be extended to others. You can think of a String, Array, Class, File or any Class that you define as behaving in much the same way. This is one of the reasons why Ruby is easier to pick up and work with than some other languages.

Comments

Popular posts from this blog

Discuss the seven characteristics of useful information.

Why have accounting software packages been designed with separate transaction modules?

A laboratory assistant prepared solution of 0.8 M, 0.6 M, 0.4 M, and 0.2 M sucrose, but forgot to label them. After realizing the error, the assistant randomly labeled the flasks containing these four unknown solutions as flask A, flask B, flask C, and flask D.