module Enumerable unless method_defined?(:sum) def sum(identity=0) inject(:+) || identity end end def drop_last(n) array = to_a return array if n > array.size array[0...(array.size - n)] end def drop_last_while return to_enum(:drop_last_while) unless block_given? result = [] dropping = true reverse_each do |value| result.unshift(value) unless dropping &&= yield(value) end result end def exactly?(n) found_count = 0 if block_given? each do |*o| found_count += 1 if yield(*o) end else each do |o| found_count += 1 if o end end (found_count > n) ? false : n == found_count end def frequencies each_with_object(Hash.new(0)) { |e, a| a[e] += 1 } end def max(identity=0) size > 0 ? sort.last : identity end def min(identity=0) size > 0 ? sort.first : identity end def mean(identity=0) collection_size = size collection_size > 0 ? inject(:+) / collection_size.to_f : identity end def median(identity=0) collection_size = size collection_sorted = sort if collection_size > 0 if collection_size % 2 == 0 (collection_sorted[(collection_size / 2) -1] + collection_sorted[collection_size / 2]) / 2.0 else collection_sorted[collection_size / 2] end else identity end end def mode(identity=0) if size > 0 frequency_distribution = inject(Hash.new(0)) { |h, v| h[v] += 1; h } frequency_top_2 = frequency_distribution.sort { |a, b| b[1] <=> a[1] }.take(2) if frequency_top_2.length == 1 frequency_top_2.first.first elsif frequency_top_2.first.last == frequency_top_2.last.last nil else frequency_top_2.first.first end else identity end end def range(identity=0) collection_sorted = sort size > 0 ? collection_sorted.last - collection_sorted.first : identity end def several? found_count = 0 if block_given? each do |*o| found_count += 1 if yield(*o) end else each do |o| found_count += 1 if o end end (found_count > 1) ? true : false end def take_last(n) array = to_a return array if n > array.size array[(array.size - n)..-1] end def take_last_while return to_enum(:take_last_while) unless block_given? result = [] reverse_each { |e| yield(e) ? result.unshift(e) : break } result end end