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

Home
Ruby
1.ActiveRecord
2.Array
3.CGI
4.Class
5.Collections
6.Database
7.Date
8.Design Patterns
9.Development
10.File Directory
11.GUI
12.Hash
13.Language Basics
14.Method
15.Network
16.Number
17.Rails
18.Range
19.Reflection
20.Statement
21.String
22.Threads
23.Time
24.Tk
25.Unit Test
26.Windows Platform
27.XML
Ruby » Collections » Enumerable 




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([12][3][4])
p ma.collect                                   # => [1234]
p ma.detect |x| x > }                      # => 4
p ma.map |x| x ** }                        # => [14916]
p ma.each_with_index |x, i| puts "Element #{i} is #{x}" }
# Element is 1
# Element is 2
# Element is 3
# Element 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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.