Is Ruby all objects, true?

Unlike JavaScript, Ruby treats basic types such as integers as objects. In addition, a class, a mechanism that regulates the behavior of an object, is also an object.

Therefore, articles for beginners are often used.

In Ruby everything is an object.

Is written. Is it true? The answer is, "It depends on the meaning of the word'all'."

Methods and blocks are not objects.

"Yeah ~? Was everything an object a lie ?!"

No, this just means that Ruby methods and blocks cannot be treated as data. It's different from Python or JavaScript.

"Yeah? Ruby Shoboy"

No, that's not the case. The method itself and the block itself are not data, but they can be converted into data and are called Method objects and Proc objects. As the name implies, they are instances of the Method and Proc classes, respectively. Of course it is an object. Since Method objects and Proc objects are data, you can of course assign them to variables, pass them as actual arguments to methods, and call the methods they have.

Proc objects can be passed to methods as actual arguments as well as blocks. Method objects can also be converted to Proc objects.

Let's look at an example.

#Using "block that squares and returns block parameters"
#Create a Proc object to square
square = proc{ |x| x * x }

#Example of calling a Proc object
p square[3] # => 9

#An example of giving a Proc object to a map as a block
p (1..3).map(&square) # => [1, 4, 9]
#→ Ratio of monoliths in the movie "2001: A Space Odyssey"

#"To to 13_Create a Method object that represents "s method call"
thirteen_to_str = 13.method(:to_s)

#Decimal string when called with no arguments
p thirteen_to_str[] # => "13"

#Octal string
p thirteen_to_str[8] # => "15"

#Stringized in binary, octal, decimal, and hexadecimal
#On the map&If you pass a Method object with, it will be converted to Proc and then
#Passed as a block.
p [2, 8, 10, 16].map(&thirteen_to_str)
# => ["1101", "15", "13", "d"]

Let's return to the first question. "Ruby is all about objects" is misleading. It should be expressed as "Ruby is all ** data ** objects".

In Ruby, variables / constants, operators, and control structures are not data, so they are not objects. The program itself is not an object. Of course, the program can be represented as a string, so it can be represented by a String object and can be executed by the eval method.

Recommended Posts

Is Ruby all objects, true?
[Ruby] What is true?
Ruby Learning # 29 Classes & Objects
What is a Ruby module?
Ruby # {} is not variable expansion
What is object-oriented after all?
[Ruby] What is `!!` used for?
[Ruby] What is an instance?
Divide by Ruby! Why is it 0?
[Ruby on Rails] What is Bcrypt?
Is there no type in Ruby?
This problem is soberly difficult ... (Ruby)
What is a Ruby 2D array?