Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - overriding/enabling multiple assignment (e.g. `a, b, c = d, e, f`)

Tags:

ruby

In ruby, you can do this:

d = [1, 2, 3]
a, b, c = d

a, b, and c, will receive the values 1, 2, and 3, respectively.

d, in this case in an Array and ruby knows to assign it's contents to a, b, and c. But, if d were a Fixnum, for example, only a would be assigned to the value of d while b and c would be assigned nil.

What properties of d allow it to be used for multiple assignment? In my exploring so far, I've only been able to make instances of subclasses of Array behave in this way.

like image 258
nicholaides Avatar asked Dec 28 '10 02:12

nicholaides


1 Answers

This is a very undocumented feature, and I'd use it with caution, but here we go. From the book The Ruby Programming Language:

When there are multiple lvalues and only a single rvalue, Ruby attempts to expand the rvalue into a list of values to assign. If the value is an array, Ruby expands the array so that each element becomes its own rvalue. If the value is not an array but implements a to_ary method, Ruby invokes that method and then expands the array it returns.

In Ruby 1.8 it is the to_ary method, in Ruby 1.9 documentation says it calls to_splat, but I haven't tested (no 1.9 in this machine)It didn't work as expected. So, you have to define a to_ary method in your object.

class Week
  def to_ary
    %w(monday tuesday wednesday thursday friday saturday sunday)
  end
end

mon, tue, wed, thu, *weekend = Week.new

* %w(...) Is a special notation for an array of words, if you are lazy to write ['monday', 'tuesday' ...]

like image 103
Chubas Avatar answered Sep 21 '22 21:09

Chubas