Assignment in Ruby is done using the equals sign (=).
colour = "red"
other_colour = String.new("blue")
number = 123
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.
You can assign values to multiple variables on one line.
colour1, colour2, colour3 = "red", "blue", "green"
colours, city = ["red", "blue", "green"], "Helsinki"
The operator ||= checks whether a variable is nil (or inexistent) and assigns an object to it if it is.
configuration ||= "default value"
| Operator | Description |
| == | Equivalency |
| != | Inequality |
| < | Less than |
| > | Greater than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
| <=> | Combined comparison operator. Returns:
|
5 == 5 # => true
5 != 4 # => true
4 > 5 # => false
4 < 5 # => true
5 <=> 5 # => 0
5 <=> 2 # => 1
5 <=> 6 # => -1
x = false
y = true
x && y # => false
x || y # => true
!x # => true
!y # => false