Posted almost 4 years ago. Visible to the public.

Ruby: How to make an object that works with multiple assignment

Ruby allows multiple assignment:

Copy
a, b, c = o

In order to prove multiple values from a single object, Ruby calls #to_a on the object:

Copy
o = String.new('O') def o.to_a [1,2,3] end a, b, c = o # Implicit call to #to_a here a # => 1 b # => 2 c # => 3

Hence, if you want your class to support multiple assignment, make sure to define a #to_a method.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
almost 2 years ago
by Henning Koch
Keywords:
array, destructuring
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more