Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Iterating over Nested Arrays

You can #flatten the Array as I have done above. For most cases, this works just fine—it’s very fast. But it’s perhaps not quite as flexible as a recursive implementation:

class Array
    def each_recur(&block)
        each do |elem|
            if elem.is_a? Array
                elem.each_recur &block
            else
                block.call elem
            end
        end
    end
end

my_ary = [[1, 2, 3, 4],[5, 6, 7, 8]]
    #=> [[1, 2, 3, 4], [5, 6, 7, 8]]

my_ary.each_recur { |elem| print(elem, " ") }

Produces:

1 2 3 4 5 6 7 8
  • + Share This
  • 🔖 Save To Your Account