Implementing Enumerable - Write One Method, Get 22 Free : Enumerable « Collections « Ruby






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

1.get Enumerable involved
2.Sorting an Array by Frequency of Appearance
3.Add cartesian to Enumerable
4.Building a Histogram
5.Call each a number of times
6.randomly each
7.Writing Block Methods that Classify or Collect
8.Enumerable.instance_methods.sort
9.Sort on two arrays