Module: Enumerable
- Defined in:
- lib/ext/enumerable.rb
Instance Method Summary collapse
- #average ⇒ Object (also: #mean, #avg)
- #map_with_index(&block) ⇒ Object
- #map_with_index!(&block) ⇒ Object
- #max_position ⇒ Object
-
#min_position ⇒ Object
Returns the position (or first position) of the minimal value.
-
#scale_with(ary) ⇒ Object
Expects an array of scalars.
- #scale_with!(ary) ⇒ Object
- #sum ⇒ Object
Instance Method Details
#average ⇒ Object Also known as: mean, avg
31 32 33 |
# File 'lib/ext/enumerable.rb', line 31 def average sum/size end |
#map_with_index(&block) ⇒ Object
2 3 4 5 6 |
# File 'lib/ext/enumerable.rb', line 2 def map_with_index(&block) val = [] self.each_with_index { |e, i| val << yield(e, i) } val end |
#map_with_index!(&block) ⇒ Object
8 9 10 11 12 13 |
# File 'lib/ext/enumerable.rb', line 8 def map_with_index!(&block) self.each_with_index do |e, i| val = yield(e, i) self[i] = val end end |
#max_position ⇒ Object
48 49 50 51 52 53 54 55 |
# File 'lib/ext/enumerable.rb', line 48 def max_position mp = [nil, nil] each_with_index do |e, i| mp = e, i unless mp.first mp = e, i if e > mp.first end mp.last end |
#min_position ⇒ Object
Returns the position (or first position) of the minimal value. So, [3,2,1,4,5,0].min_position is 5
39 40 41 42 43 44 45 46 |
# File 'lib/ext/enumerable.rb', line 39 def min_position mp = [nil, nil] each_with_index do |e, i| mp = e, i unless mp.first mp = e, i if e < mp.first end mp.last end |
#scale_with(ary) ⇒ Object
Expects an array of scalars
16 17 18 19 20 |
# File 'lib/ext/enumerable.rb', line 16 def scale_with(ary) val = [] self.map_with_index { |e, i| val << e * ary[i] } val end |
#scale_with!(ary) ⇒ Object
22 23 24 |
# File 'lib/ext/enumerable.rb', line 22 def scale_with!(ary) self.map_with_index! { |e, i| e * ary[i] } end |
#sum ⇒ Object
26 27 28 29 |
# File 'lib/ext/enumerable.rb', line 26 def sum val = any? {|e| e.is_a?(Float)} ? 0.0 : 0 self.inject(val) {|s, e| s += e} end |