Module: Enumerable

Defined in:
lib/enumerable/extra.rb

Constant Summary collapse

EXTRA_VERSION =

The version of the enumerable-extra library.

'0.2.0'

Instance Method Summary collapse

Instance Method Details

#map(method = nil, *args, &block) ⇒ Object Also known as: collect

Returns a new array containing the results of running method once for every element in the enumerable object. If both arguments and a block are provided the arguments are processed first, then passed to the block.

If no method argument is provided, then it behaves as the standard MRI method.

Examples:

array = ['foo', 'bar']

# No arguments
array.map(:capitalize) => ['Foo', 'Bar']

# With arguments
array.map(:+, 'x') => ['foox', 'barx']

# With arguments and a block
array.map(:capitalize){ |e| e + 'x' } => ['Foox', 'Barx']

Note that for 1.9.x users, Enumerator objects are converted explicitly back into arrays.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/enumerable/extra.rb', line 42

def map(method=nil, *args, &block)
  if method
    array  = []
    method = method.to_sym unless method.is_a?(Symbol)

    each{ |obj|
      temp = obj.send(method, *args)
      if block
        array << block.call(temp)
      else
        array << temp
      end
    }

    # Convert enumerators back to arrays for 1.9.x
    RUBY_VERSION.to_f >= 1.9 ? array.to_a : array
  else
    RUBY_VERSION.to_f ? old_map(&block).to_a : old_map(&block)
  end
end

#old_mapObject



6
# File 'lib/enumerable/extra.rb', line 6

alias old_map map

#sum(total = 0) ⇒ Object

Returns the numeric total of the elements of enum, using total as an accumulator (0 by default). Raises an error if any of the elements are non-numeric.



13
14
15
16
# File 'lib/enumerable/extra.rb', line 13

def sum(total = 0)
  each{ |val| total += val }
  total
end