␡
- Slicing an Array
- Iterating over an Array
- Creating Enumerable Classes
- Sorting an Array
- Iterating over Nested Arrays
- Modifying All the Values in an Array
- Sorting Nested Arrays
- Building a Hash from a Config File
- Sorting a Hash by Key or Value
- Eliminating Duplicate Data from Arrays (Sets)
- Working with Nested Sets
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