File: enumx.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (116 lines) | stat: -rw-r--r-- 1,844 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# = FILE
#
#   elementwise.rb
#
# = DESCRIPTION
#
#   Elementwise extensions to Enumerable.
#
# = AUTHORS
#
#   CREDIT Martin DeMello
#   CREDIT Sean O'Halpin
#
# = NOTES
#
#   NOTE Deprecated #~@ alias for elementwise.

require 'enumerator'

class Enumerable::Enumerator
  alias init initialize

  def initialize(*args)
    @enum_obj, @enum_meth = *args
    @enum_meth ||= :each
    init(*args)
  end

  def method_missing(sym,*args,&blk)
    each{ |x| x.send(sym,*args,&blk) }
  end
end

class Enumerable::Elementor < Enumerable::Enumerator
  def method_missing(sym,*args,&blk)
    each{ |x| x.send(sym,*args,&blk) }.to_elem(@enum_meth)
  end
end

#
module Enumerable

  def to_elem(op)
    Enumerable::Elementor.new(self,op)
  end

  ops = %w{map select reject detect find collect}

  ops.each do |op|
    module_eval %{
      alias _#{op} #{op}

      def #{op}(&b)
        if block_given?
          _#{op}(&b)
        else
          to_enum(:#{op})
        end
      end

      def #{op}x(&b)
        if block_given?
          #{op}(&b)
        else
          to_elem(:#{op})
        end
      end
    }
  end

end

class Array

  ENUM_METHODS = {}

  ["map", "reject", "collect", "select"].each{ |m|
    ENUM_METHODS[m.to_sym] = instance_method(m)
  }

  ENUM_METHODS.keys.each do |op|
    module_eval %{
      def #{op}(&b)
        if block_given?
          ENUM_METHODS[:#{op}].bind(self).call(&b)
        else
          to_enum(:#{op})
        end
      end

      def #{op}x(&b)
        if block_given?
          ENUM_METHODS[:#{op}].bind(self).call(&b)
        else
          to_elem(:#{op})
        end
      end
    }
   end
end

#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TestElemental < Test::Unit::TestCase

  end

=end