Thanks Ruby – Array zip fail   no comments

Posted at 5:33 pm in Ruby

After updating rails from 2.0.2 to 2.2.2 on the bit-tech CMS this week I discovered a bug that had cropped up in one of my controllers where I was calling zip to join a a has_many collection with a couple of arrays and iterate through them. The code that was working fine now did something like the following.

>> g.groups.zip([1,2], [3,4]) {|a,b,c| p a.inspect + ‘, ‘ + b.inspect + ‘, ‘ + c.inspect }
“[#<Group id: 1>, 1, 3], nil, nil”
“[#<Group id: 2>, 2, 4], nil, nil”

This is strange, I can no longer access the three elements of the array directly in the block. So I tried the following

>> g.groups.to_a.zip([1,2], [3,4]) {|a,b,c| p a.inspect + ‘, ‘ + b.inspect + ‘, ‘ + c.inspect }
“#<Group id: 1>, 1, 3″
“#<Group id: 2>, 2, 4″

As you can see this solved the problem, but I was confused why there was a difference so I executed…

>> g.groups.class
=> Array

Why when I cast it to an Array, from an Array, is it acting differently? Rails must have done something to the Array class that is returned by the has_many relationship.

Written by Jamie on December 12th, 2008

Tagged with ,

Leave a Reply