Operator Expressions
Example:
Some method calls and control structures take the form of operators for ease in programming. Ruby contains the following operators:
"High" and "low" signify the operators' priority level. For example, "&&" has a higher priority than "||", so it would be interpreted in the following way:
Most operators are method calls in special form, but some are built into the language and cannot be redefined.
Redefinable operators (methods)
+@ and -@ represent the unary operators + and -. This notation is used in method definitions and the like.
Nonredefinable operators (control structures)
Combination operators (i.e., self-assignment operators, !=, and !~) cannot be redefined.
Assignment
Example:
Syntax:
Assignment expressions are used to assign values to variables and the like. Assignments can also be used as declarations for local variables or constants. The left side of an assignment expression must be one of the following:
a variable
If there is a variable on the left side, the value of the expression is assigned to the variable.
an array reference
For the object obtained by evaluating expr1, this form is converted into a []= method call with expr2 through exprN as arguments.
an attribute reference
For the object obtained by evaluating expr1, calls the identifier= method with expr2 as an argument.
Attributes can be defined with attr_accessor in the same way:
Self-Assignment
Example:
Syntax:
op is one of the following. There can be no space between the operator and =.
In this assignment format, most cases are evaluated as:
Multiple Assignment
Example:
Syntax:
Multiple assignment performs assignments from multiple expressions or arrays. Each expression on the left must be assignable. If there is only one expression on the right, its value will be converted into an array whose elements will be assigned to the expressions on the left. If there are more elements in the array than on the left, the extra elements are ignored. If there are too few elements in the array, nil will be assigned to the extra elements on the left.
Prepend * to the final expression on the left to assign all extra lefthand elements to that expression as an array. If there are no extra elements, an empty array will be assigned.
and
Example:
Syntax:
First evaluates the left side; if the result is true, evaluates the right side. and does the same as &&, but is a lower priority operator.
or
Example:
Syntax:
First evaluates the left side; if the result is false, evaluates the right side. or does the same as ||, but is a lower priority operator.
not
Example:
Syntax:
If the value of the expression is true, returns FALSE; if the value is false, returns TRUE.
The following notation is also possible:
Conditional Operators
Example:
Syntax:
Returns expr2 or expr3 depending on the results of expr1. This is identical to:
Last updated