Assignment Operators

suggest change

Simple Assignment

= is a simple assignment. It creates a new local variable if the variable was not previously referenced.

x = 3y = 4 + 5puts "x is #{x}, y is #{y}"

This will output:

x is 3, y is 9

Parallel Assignment

Variables can also be assigned in parallel, e.g. x, y = 3, 9. This is especially useful for swapping values:

x, y = 3, 9x, y = y, xputs "x is #{x}, y is #{y}"

This will output:

x is 9, y is 3

Abbreviated Assignment

It’s possible to mix operators and assignment. For example:

x = 1y = 2puts "x is #{x}, y is #{y}"x += yputs "x is now #{x}"

Shows the following output:

x is 1, y is 2
x is now 3

Various operations can be used in abbreviated assignment:

Operator | Description | Example | Equivalent to | —— | —— | —— | —— |+= | Adds and reassigns the variable | x += y | x = x + y |-= | Subtracts and reassigns the variable | x -= y | x = x - y |*= | Multiplies and reassigns the variable | x *= y | x = x * y |/= | Divides and reassigns the variable | x /= y | x = x / y |%= | Divides, takes the remainder, and reassigns the variable | x %= y | x = x % y |**= | Calculates the exponent and reassigns the variable | x **= y | x = x ** y |

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents