Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/pru/core_ext/array.rb
Instance Method Summary collapse
- #group_by ⇒ Object
- #grouped ⇒ Object
- #mean(method = nil, &block) ⇒ Object
- #sum(method = nil, &block) ⇒ Object
Instance Method Details
#group_by ⇒ Object
22 23 24 25 26 |
# File 'lib/pru/core_ext/array.rb', line 22 def group_by hash = {} each { |x| hash[yield(x)] = x } hash end |
#grouped ⇒ Object
18 19 20 |
# File 'lib/pru/core_ext/array.rb', line 18 def grouped group_by { |x| x } end |
#mean(method = nil, &block) ⇒ Object
14 15 16 |
# File 'lib/pru/core_ext/array.rb', line 14 def mean(method = nil, &block) sum(method, &block) / size.to_f end |
#sum(method = nil, &block) ⇒ Object
3 4 5 6 7 8 9 10 11 12 |
# File 'lib/pru/core_ext/array.rb', line 3 def sum(method = nil, &block) if block_given? raise ArgumentError, "You cannot pass a block and a method!" if method inject(0) { |sum, i| sum + yield(i) } elsif method inject(0) { |sum, i| sum + i.send(method) } else inject(0) { |sum, i| sum + i } end end |