Sha256: d367f813fe595c8bbd96df27e1e9303cae62fd0d1b67c437a82faa85bd70f125

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 KB

Contents

#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
# Copyright Steffie Dorn <mail@muflax.com>, 2013
# License: GNU GPL 3 <http://www.gnu.org/copyleft/gpl.html>

module Enumerable
  def average
    self.sum.to_f / self.size.to_f
  end
  alias :mean :average
  alias :avg  :average

  def geometric_mean
    self.reduce(:*).to_f ** (1.0 / self.size.to_f)
  end

  def median
    self.percentile 0.5
  end

  def median_by &block
    self.percentile_by 0.5, &block
  end

  def percentile percent
    self.sort[(self.size * percent).round]
  end

  def percentile_by percent, &block
    self.sort_by(&block)[(self.size * percent).round]
  end

  def triangle
    self.to_a.triangle
  end

  def histogram &block
    histo = vivaHash 0
    self.each do |el|
      histo[block.call(el)] += 1
    end

    histo
  end

  def count_by &block
    self.histogram(&block).sort_by(&:second).to_h
  end

  def rfind *arg, &block
    self.reverse.find(*arg, &block)
  end

  def to_ratio
    sum = self.sum
    self.map{|n| (n.to_f / sum).round(1)}
  end

  def to_percent
    sum = self.sum / 100.0
    self.map{|n| (n.to_f / sum).round(1)}
  end

  def with_previous
    self.reduce(nil){|prev, cur| yield prev, cur; cur}; self
  end
end

class Object
  def in? other
    other.include?(self)
  rescue NoMethodError
    raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
muflax-0.5.5 lib/muflax/enumerable.rb
muflax-0.5.3 lib/muflax/enumerable.rb
muflax-0.5.2 lib/muflax/enumerable.rb