Wednesday, May 18, 2011

in_groups vs in_groups_of

I was looking through the methods for arrays in active support and found in_groups. I already knew about in_groups_of so, naturally, I thought, "what does in_groups do?"
%w(a b c d e f g h i j k l m).in_groups(4)
splits an array into 4 groups of 4 elements (use on bigger arrays to really get a feel for what it does.
[["a", "b", "c", "d"], ["e", "f", "g", nil], ["h", "i", "j", nil], ["k", "l", "m", nil]]

%w(a b c d e f g h i j k l m).in_groups_of(4)
splits the array into groups of 4 elements (again, bigger arrays will give you a better idea)
[["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"], ["m", nil, nil, nil]]

If you wanted all those nil values to go away, just pass false as a second parameter to either of these functions. You can also just fill in nil with any other object by passing that object instead of false.

No comments:

Post a Comment