Operator Expressions

Example:

1+2*3/4

Some method calls and control structures take the form of operators for ease in programming. Ruby contains the following operators:

high   ::
       []
       **
       -(unary)  +(unary)  !  ~
       *  /  %
       +  -
       << >>
       &
       |  ^
       > >=  < <=
       <=> ==  === !=  =~  !~
       &&
       ||
       ..  ...
       ?:(conditional operator)
       =(+=, -= ... )
       not
low    and or

"High" and "low" signify the operators' priority level. For example, "&&" has a higher priority than "||", so it would be interpreted in the following way:

a && b || c   # => (a && b) || c
a || b && c   # =>  a || (b && c)

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.

    =  ?:  ..  ...  !  not  &&  and  ||  or  ::

Assignment

Example:

foo = bar
foo[0] = bar
foo.bar = baz

Syntax:

variable '=' expr
constant '=' expr
expr '['expr..']' '=' expr
expr '.' identifier '=' expr

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

    variable '=' expr

    If there is a variable on the left side, the value of the expression is assigned to the variable.

  • an array reference

    expr1 '[' expr2 ... ']' '=' exprN

    For the object obtained by evaluating expr1, this form is converted into a []= method call with expr2 through exprN as arguments.

    class C
      def initialize
        @ary = [0,1,2,3,4,5,6,7]
      end
      def [](i)
        @ary[i * 2]
      end
      def []=( i, v )
        @ary[i * 2] = v
      end
    end
    c = C.new
    p c[3]      # converted to c.[]( 3 ); result is 6
    p c[3] = 1  # converted to c.[]=(3,1); result is 1
  • an attribute reference

    expr1 '.' identifier '=' expr2

    For the object obtained by evaluating expr1, calls the identifier= method with expr2 as an argument.

    class C
      def foo
        @foo
      end
      def foo=( v )
        @foo = v
      end
    end
    c = C.new
    c.foo = 5   # converted to c.foo=( 5 )
    p c.foo     # => 5

    Attributes can be defined with attr_accessor in the same way:

    class C
      attr_accessor :foo
    end
    c = C.new
    c.foo = 5   # converted to c.foo=( 5 )
    p c.foo     # => 5

Self-Assignment

Example:

foo += 12       # foo = foo + 12
foo *= 3        # foo = foo * 3

Syntax:

expr1 op= expr2     # expr1 is part of the right-hand assignment

op is one of the following. There can be no space between the operator and =.

+, -, *, /, %, **, &, |, ^, <<, >>, &&, ||

In this assignment format, most cases are evaluated as:

expr1 = expr1 op expr2

Multiple Assignment

Example:

foo, bar, baz = 1, 2, 3
foo, = list()
foo, *rest = list2()

Syntax:

expr [',' [ expr ',' ... ] ['*' [ expr ]]] = expr [, expr ... ]['*' expr ]
'*' [ expr ] = expr [, expr ... ]['*' expr ]

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.

foo, bar  = [1, 2]      # foo = 1; bar = 2
foo, bar  = 1, 2        # foo = 1; bar = 2
foo, bar  = 1           # foo = 1; bar = nil
foo, bar  = 1, 2, 3     # foo = 1; bar = 2
foo       = 1, 2, 3     # foo = [1, 2, 3]
*foo      = 1, 2, 3     # foo = [1, 2, 3]
foo, *bar = 1, 2, 3     # foo = 1; bar = [2, 3]

and

Example:

test && set
test and set

Syntax:

expr '&&' expr
expr and expr

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:

demo || die
demo or die

Syntax:

expr '||' expr
expr or expr

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:

! me
not me
i != you

Syntax:

'!' expr
not expr

If the value of the expression is true, returns FALSE; if the value is false, returns TRUE.

The following notation is also possible:

expr '!=' expr          # same as !(expr == expr)
expr '=~' expr          # same as !(expr =~ expr)

Conditional Operators

Example:

obj == 1 ? foo : bar

Syntax:

expr1 ? expr2 : expr3

Returns expr2 or expr3 depending on the results of expr1. This is identical to:

if expr1 then expr2 else expr3 end

Last updated