Last active
February 19, 2019 18:55
-
-
Save kyletolle/9163327 to your computer and use it in GitHub Desktop.
deep_each.rb - a multidimensional each for Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
two_d_grid = | |
[ | |
[ 1, 2, 3, 4, 5 ], | |
[ 6, 7, 8, 9, 10 ], | |
[ 11, 12, 13, 14, 15] | |
] | |
puts "Basic 2D each" | |
two_d_grid.each do |row| | |
row.each do |cell| | |
puts "Cell: #{cell}" | |
end | |
end | |
three_d_grid = | |
[ | |
[ | |
[ 1, 2, 3], | |
[ 4, 5, 6] | |
], | |
[ | |
[ 7, 8, 9], | |
[10, 11, 12] | |
], | |
[ | |
[13, 14, 15], | |
[16, 17, 18] | |
] | |
] | |
puts "Basic 3D each" | |
three_d_grid.each do |plane| | |
plane.each do |row| | |
row.each do |cell| | |
puts "Cell: #{cell}" | |
end | |
end | |
end | |
uneven_dimensional_grid = | |
[ | |
1, | |
[2, 3, 4], | |
[ | |
[5, 6, 7], | |
[8, 9, 10] | |
], | |
11, | |
[ | |
[ | |
[12], | |
13 | |
], | |
14 | |
], | |
15 | |
] | |
def deep_each(object, &block) | |
traverser = lambda do |obj| | |
if obj.respond_to?(:each) | |
obj.each(&traverser) | |
else | |
block.call obj | |
end | |
end | |
traverser.call object | |
end | |
puts "2D deep each" | |
deep_each(two_d_grid) do |cell| | |
puts "Cell: #{cell}" | |
end | |
puts "3D deep each" | |
deep_each(three_d_grid) do |cell| | |
puts "Cell: #{cell}" | |
end | |
puts "Uneven D deep each" | |
deep_each(uneven_dimensional_grid) do |cell| | |
puts "Cell: #{cell}" | |
end | |
module Enumerable | |
def deep_each(&block) | |
traverser = lambda do |obj| | |
if obj.respond_to?(:each) | |
obj.each(&traverser) | |
else | |
block.call obj | |
end | |
end | |
traverser.call self | |
end | |
end | |
puts "Monkeypatched Enumerable deep each" | |
uneven_dimensional_grid.deep_each do |cell| | |
puts "Cell: #{cell}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment