Ruby on Rails Course 2009

Ruby: Operators

Assignment

Assignment in Ruby is done using the equals sign (=).

colour = "red"
other_colour = String.new("blue")
number = 123

Self Assignment

x = 1           # => 1
x += x          # => 2
x -= x          # => 0
x += 4          # => 4
x *= x          # => 16
x **= x         # => 18446744073709551616 # Raise to the power
x /= x          # => 1

There are no increment/decrement operators in Ruby.

Multiple Assignment

You can assign values to multiple variables on one line.

colour1, colour2, colour3 = "red", "blue", "green"
colours, city = ["red", "blue", "green"], "Helsinki"

Conditional Assignment

The operator ||= checks whether a variable is nil (or inexistent) and assigns an object to it if it is.

configuration ||= "default value"

Comparison Operators

Operator Description
== Equivalency
!= Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
<=> Combined comparison operator. Returns:

  • 0 if the values are equal

  • -1 if the second is greater than the first

  • 1 if the first is greater than the second

Comparison Operators

Examples

5 == 5      # => true
5 != 4      # => true
4 > 5       # => false
4 < 5       # => true
5 <=> 5     # => 0
5 <=> 2     # => 1
5 <=> 6     # => -1

And (&&), Or (||), Not (!)

x = false
y = true

x && y    # => false
x || y    # => true
!x        # => true
!y        # => false