Operators
- Operators can be redefined
- Ruby has no increment / decrement
operators
- The method-call dot operator (".") has
the highest precedence
- Ruby variables hold references to
objects; the = operator copies the references; there's no standard,
built-in deep copy in Ruby; serialization/marshalling can be used to
simulate a deep copy
Arithmetic
Binary operators
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
Unary operators
- Unary negation (reverses the sign)
Assignment
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
**= Exponent and assign
||= Assign if the lvalue is nil (may not be available for class variables)
a += b internally resolves
to a = a + b
Parallel assignment
a, b = b, a # Safely swap the values of a and b
- Arrays can be collapsed and expanded
using parallel assignment
Comparison
== Equal
!= Not equal
> Greater than
>= Greather than or equal to
< Less than
<= Less than or equal to
<=> Comparison operator (returns -1, 0, or +1)
=== Used to test equality within a when clause of a case statement
eql? True if both have the same type and equal values
equal? True if both have the same object id
==, ===, <=>,
=~, eql?, and equal?
are typically overridden by built-in classes to provide the appropriate
semantics (i.e. using == to compare two arrays)
a != b internally resolves
to !(a == b)
Conditional
? : Ternary comparison operator
condition ? val1 : val2 (Evaluates val1 if condition is true; otherwise, evaluates val2)
Boolean
- Short-circuit logical operations
- Evaluates the minimal number of
expressions necessary
- Partial evaluation (rather than full
evaluation)
and
or
not
&&
||
!
defined? expr
defined? returns a
description of the
expression, or nil is the expression is undefined
- [
ot, and, or have
lower precedence than !, &&, ||
Bitwise
Binary operators
& And
| Or
^ Xor
<< Shift left (zero fill)
>> Shift right (sign-propogating); copies of the leftmost bit (sign bit) are shifted in from the left.
Unary operators
~ Not (inverts the bits)
String
= Assignment
+ Concatenation
+= Concatenate and assign
Array
= Assignment
+ Concatenation
+= Concatenate and assign
<< Append an object to the array (myArray << 3 << 4)
Command expansion
`expr` # back quotes
- The expression is executed by the
underlying operating system
- The value of the expression is the
standard output of the command
$? contains the exit status
of the command
Match operator
=~
!~ Logical negation of =~
a !~ /b/ internally resolves
to !(a =~
/b/)