Our Daily Method #7: Enumerable#mjoin

Geplaatst door Michiel de Mare wo, 13 feb 2008 08:00:00 GMT

You all know flatten. Flatten takes an array and removes all structure from it. But sometimes you’ve got an array of arrays of arrays, and want to turn it into an array of arrays. What we need is a flatten-light: mjoin

module Enumerable
  def mjoin
    inject!([]) {|memo,x| a.each {|x| memo << x}}
  end
end
(read more about inject!).

When do you use this? Whenever you want to use map but you don’t always want to return exactly one value, and some or all of the values are arrays (which means you can’t use flatten).

Does that sound exceedlingly rare? In fact, it is a very common structure. A table is an array of arrays, and a join is an operation which returns zero or more results per row. And this also explains the name! (join, of course, is already taken – mjoin was inspired by this article).

I plan to talk more about using the table datastructure in the near future.

Recommend Michiel de Mare

Geplaatst in , ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning