Read more

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

Dominik Schöler
October 05, 2015Software engineer at makandra GmbH

Ruby allows multiple assignment:

a, b, c = o
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2015-10-05 13:18)