A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.ruby-lang.org/en/3.3/syntax/operators_rdoc.html below:

operators - Documentation for Ruby 3.3

Operators

In Ruby, operators such as +, are defined as methods on the class. Literals define their methods within the lower level, C language. String class, for example.

Ruby objects can define or overload their own implementation for most operators.

Here is an example:

class Foo < String
  def +(str)
    self.concat(str).concat("another string")
  end
end

foobar = Foo.new("test ")
puts foobar + "baz "

This prints:

test baz another string

What operators are available is dependent on the implementing class.

Operator Behavior

How a class behaves to a given operator is specific to that class, since operators are method implementations.

When using an operator, it’s the expression on the left-hand side of the operation that specifies the behavior.

'a' * 3         
3 * 'a'         
Logical Operators

Logical operators are not methods, and therefor cannot be redefined/overloaded. They are tokenized at a lower level.

Short-circuit logical operators (&&, ||, and, and or) do not always result in a boolean value. Similar to blocks, it’s the last evaluated expression that defines the result of the operation.

&&, and

Both &&/and operators provide short-circuiting by executing each side of the operator, left to right, and stopping at the first occurrence of a falsey expression. The expression that defines the result is the last one executed, whether it be the final expression, or the first occurrence of a falsey expression.

Some examples:

true && 9 && "string"                       
(1 + 2) && nil && "string"                  
(a = 1) && (b = false) && (c = "string")    

puts a                                      
puts b                                      
puts c                                      

In this last example, c was initialized, but not defined.

||, or

The means by which ||/or short-circuits, is to return the result of the first expression that is truthy.

Some examples:

(1 + 2) || true || "string"                 
false || nil || "string"                    

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4