[Bug #20482] [DOC] Clarify about pattern maching guard clause
[ruby.git] / doc / syntax / operators.rdoc
blobd3045ac99e35b3119dfb62c8ece6268626389bd2
1 = Operators
3 In Ruby, operators such as <code>+</code>, are defined as methods on the class.
4 Literals[rdoc-ref:syntax/literals.rdoc] define their methods within the lower
5 level, C language. String class, for example.
7 Ruby objects can define or overload their own implementation for most operators.
9 Here is an example:
11   class Foo < String
12     def +(str)
13       self.concat(str).concat("another string")
14     end
15   end
17   foobar = Foo.new("test ")
18   puts foobar + "baz "
20 This prints:
22   test baz another string
24 What operators are available is dependent on the implementing class.
26 == Operator Behavior
28 How a class behaves to a given operator is specific to that class, since
29 operators are method implementations.
31 When using an operator, it's the expression on the left-hand side of the
32 operation that specifies the behavior.
34   'a' * 3         #=> "aaa"
35   3 * 'a'         # TypeError: String can't be coerced into Integer
37 == Logical Operators
39 Logical operators are not methods, and therefore cannot be
40 redefined/overloaded. They are tokenized at a lower level.
42 Short-circuit logical operators (<code>&&</code>, <code>||</code>,
43 <code>and</code>, and <code>or</code>) do not always result in a boolean value.
44 Similar to blocks, it's the last evaluated expression that defines the result
45 of the operation.
47 === <code>&&</code>, <code>and</code>
49 Both <code>&&</code>/<code>and</code> operators provide short-circuiting by executing each
50 side of the operator, left to right, and stopping at the first occurrence of a
51 falsey expression. The expression that defines the result is the last one
52 executed, whether it be the final expression, or the first occurrence of a falsey
53 expression.
55 Some examples:
57   true && 9 && "string"                       #=> "string"
58   (1 + 2) && nil && "string"                  #=> nil
59   (a = 1) && (b = false) && (c = "string")    #=> false
61   puts a                                      #=> 1
62   puts b                                      #=> false
63   puts c                                      #=> nil
65 In this last example, <code>c</code> was initialized, but not defined.
67 === <code>||</code>, <code>or</code>
69 The means by which <code>||</code>/<code>or</code> short-circuits, is to return the result of
70 the first expression that is truthy.
72 Some examples:
74   (1 + 2) || true || "string"                 #=> 3
75   false || nil || "string"                    #=> "string"