Everything in Ruby is an object?

Tram Ho

“Everything in Ruby is an object” is a statement that almost every Rubiers has heard. But Einstein’s theory of relativity says: Nothing is absolute!

Hmmm, so let’s see, is there anything in Ruby that isn’t an object?

1. Block

Block is a block of sequentially executed statements enclosed in {} or do end . Block is not an object, and therefore, it has no name. It also cannot be assigned to any variables. Blocks cannot be reused and cannot be stored. Block is passed to a method and is executed at the keyword yeild

2. Conditional

Conditional makes it possible to execute statements according to the desired condition. In Ruby, there are two commonly used conditionals: If - else and case - when . So what’s the difference between these 2 items? When to use if - else , when to use case - when ?

a. if – else

If – else is a conditional type that is evaluated sequentially from top to bottom, and it only executes statements in the conditional branch that is satisfied. With if - else , we can consider many different conditions or combinations of conditions, and the preceding conditions will be evaluated first.

According to the above example, it is clear that when passing 3 and 4 in, it satisfies the condition < 5 . However, it has satisfied the condition > 2 before, so it will not consider the conditions below.

b. case – when

case - when is also a conditional statement. However, this statement can only compare with 1 variable and each expression is a unique value. The values ​​to be compared in the expression can be a number, a string, a symbol or even an array

c. When to use If - else , when to use when - case ?

if - else can be used for all cases. However, when the conditional expressions are single expressions and have independent, non-overlapping values, we should use when - case to make the code more neat and easy to understand.

3. Methods

Methods can simply be understood as the actions of an object, and therefore it is not an object.

4. Operators

Operators is a set of operators used to perform operations with objects. In fact, these operators are methods. And when performing the math a + b , in fact + is the method of a , and b is the argument. And because it is a method, we can completely override these operators.

Like the example above, I have overridden the + operator on my own object a(class String). And now the result of a + ... will always include the string Xuan Tai


Through this, we can already know that, in Ruby not all are objects. Which is more precise: In Ruby, almost everything is an object.

Thank you readers, if there is something wrong with my article, please feel free to scold me. I will always humble myself to listen to have the opportunity to gain more knowledge. Thank you.

Share the news now

Source : Viblo