First of all, <
and <<
are not the same.
Ruby – like many other programming languages – uses the infix notation for binary operators, i.e.:
left-hand side operator right-hand side
For example:
1 + 2
a - b
i >= j
x << y
But unlike many other languages, operators are implemented as methods in Ruby. So it's actually:
receiver method argument
If you want to know, what alarms << AlarmMonitor.new(...)
does, you have to know what kind of object alarms
is. In your example, it's an array (alarms = []
) so the method is Array#<<
:
ary << obj → ary
Append—Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together.
Note that different objects (or classes) can implement the same operator in different ways:
a = [1, 2]
a << 3 # pushes 3 onto the array, i.e. [1, 2, 3]
d = Date.new(2020, 5, 28)
d << 3 # returns a date 3 months earlier, i.e. 2020-02-28
i = 0b00001011
i << 3 # shifts the bits 3 to the left, i.e. 0b01011000
The behavior primarily depends on the receiver.
Let's briefly get back to <
. In addition to methods, Ruby has keywords. Keywords sometimes work like methods, but they have their own parsing rules.
For class creation, Ruby has the class
keyword:
class MyClass
# ...
end
Which accepts an optional subclass via:
class MySubclass < MyClass
# ...
end
Here, <
is not an operator, but part of the class
keyword syntax.
However, there's also a <
operator for classes: Module#<
. It can be used to check whether MySubclass
is a subclass of MyClass
: (thus mirroring the class creation syntax)
MySubclass < MyClass
#=> true