Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/enumerable/extra.rb
Instance Method Summary collapse
-
#map(method = nil, *args, &block) ⇒ Object
(also: #collect)
Returns a new array containing the results of running
block
once for every element in thearray
. -
#map!(method = nil, *args, &block) ⇒ Object
(also: #collect!)
Same as Array#map, but modifies the receiver in place.
- #old_map ⇒ Object
- #old_map! ⇒ Object
Instance Method Details
#map(method = nil, *args, &block) ⇒ Object Also known as: collect
Returns a new array containing the results of running block
once for every element in the array
.
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']
– The Array class actually has its own implementation of the map
method, hence the duplication.
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/enumerable/extra.rb', line 86 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 } array else old_map(&block) end end |
#map!(method = nil, *args, &block) ⇒ Object Also known as: collect!
Same as Array#map, but modifies the receiver in place. Also note that a block is not required. If no block is given, an array of values is returned instead
109 110 111 |
# File 'lib/enumerable/extra.rb', line 109 def map!(method=nil, *args, &block) self.replace(map(method, *args, &block)) end |
#old_map ⇒ Object
61 |
# File 'lib/enumerable/extra.rb', line 61 alias old_map map |
#old_map! ⇒ Object
62 |
# File 'lib/enumerable/extra.rb', line 62 alias old_map! map! |