In this post I’d like to discuss one of the more interesting aspects of the Ruby programming language, which is that most of the ‘operators’ in ruby are actually methods. Here is a list of some of the more common fake operators.

[], []=, <, >, ==, +, -, *, \,  %

What does this mean and why does it matter? It means that when you call one of the above ‘operators’, you are actually calling a method. This matters because each class can have its own implementation of a method, meaning the same method may behave differently depending on the class of the object it is called on. This is the reason the following code works.

Output: 

5
ab

Although this code seems trivially simple, there are a lot of things happening. On the first line the method Integer#+ is called on 2 with an argument of 3. The return value of this method, 5, is saved to the variable via the assignment operator (= is a real operator and not a method). This is the expected result, since we associate + with addition. However, what about ‘a’ + ‘b’? We only get the result of ab because a different method,String#+, was called. Rather than adding two numbers, this method joins two strings together. It may seem like it doesn’t matter if something is a method or an operator as long as it works the way we expect it to. In some cases that’s true, but the main reason to understand the difference is because _methods can be overwritten! _Here’s an example that will get you immediately fired from your programming job.

#software-development #software #software-engineering #ruby #programming

Ruby: Fake Operators
1.50 GEEK