Assignment

Almost every example we’ve given so far in this book has featured assignment. It’s about time we said something about it.

An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue). It then returns that rvalue as the result of the assignment expression. This means you can chain assignments, and you can perform assignments in some unexpected places:

 a = b = 1 + 2 + 3
 a ​# => 6
 b ​# => 6
 a = (b = 1 + 2) + 3
 a ​# => 6
 b ​# => 3
 
 File.​open​(name = gets.​chomp​)

Ruby has two basic forms of assignment. The first assigns an object reference to a variable or constant. This form of assignment is hardwired into the language:

 instrument = ​"piano"
 MIDDLE_A ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.