Implementing Enumerable - Write One Method, Get 22 Free
class MultiArray
include Enumerable
def initialize(*arrays)
@arrays = arrays
end
def each
@arrays.each { |a| a.each { |x| yield x } }
end
end
ma = MultiArray.new([1, 2], [3], [4])
p ma.collect # => [1, 2, 3, 4]
p ma.detect { |x| x > 3 } # => 4
p ma.map { |x| x ** 2 } # => [1, 4, 9, 16]
p ma.each_with_index { |x, i| puts "Element #{i} is #{x}" }
# Element 0 is 1
# Element 1 is 2
# Element 2 is 3
# Element 3 is 4
Related examples in the same category