Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/enumerable/extra.rb
Instance Method Summary collapse
-
#each(*others, &block) ⇒ Object
Iterates over each element in the array, yielding the result.
-
#map(method = nil, *args, &block) ⇒ Object
(also: #collect)
Returns a new array containing the results of running
blockonce for every element in thearray. -
#map!(method = nil, *args, &block) ⇒ Object
(also: #collect!)
Same as Array#map, but modifies the receiver in place.
- #old_each ⇒ Object
-
#old_map ⇒ Object
These methods are defined separately in array.c, and they are not actual aliases, so we must alias them each separately from Enumerable.
- #old_map! ⇒ Object
Instance Method Details
#each(*others, &block) ⇒ Object
Iterates over each element in the array, yielding the result. When no arguments are provided this behaves as the standard Array#each. With arguments it behaves the same as Array#zip.
131 132 133 134 135 136 137 |
# File 'lib/enumerable/extra.rb', line 131 def each(*others, &block) if others.nil? || others.empty? old_each(&block) else zip(*others, &block) end end |
#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']
Note that for 1.9.x users, Enumerator objects are converted explicitly back into arrays. – The Array class actually has its own implementation of the map method, hence the duplication.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/enumerable/extra.rb', line 99 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 } RUBY_VERSION.to_f >= 1.9 ? array.to_a : array else RUBY_VERSION.to_f >= 1.9 ? old_map(&block).to_a : 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
123 124 125 |
# File 'lib/enumerable/extra.rb', line 123 def map!(method=nil, *args, &block) self.replace(map(method, *args, &block)) end |
#old_each ⇒ Object
75 |
# File 'lib/enumerable/extra.rb', line 75 alias old_each each |
#old_map ⇒ Object
These methods are defined separately in array.c, and they are not actual aliases, so we must alias them each separately from Enumerable.
71 |
# File 'lib/enumerable/extra.rb', line 71 alias old_map map |
#old_map! ⇒ Object
72 |
# File 'lib/enumerable/extra.rb', line 72 alias old_map! map! |