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

Posted Over 8 years ago. Visible to the public.

Ruby allows multiple assignment:

a, b, c = o

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

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.

Dominik Schöler
Last edit
Over 6 years ago
Henning Koch
Keywords
array, destructuring
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2015-10-05 11:18)