Sha256: 5f43ca9611abfe5090ee852844f91b12cd13814a7f65a7ef3e0022fb6146c0a9

Contents?: true

Size: 1.37 KB

Versions: 3

Compression:

Stored size: 1.37 KB

Contents

#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
# Copyright Freya Dorn <freya.siv.dorn@gmail.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.7.0 lib/muflax/enumerable.rb
muflax-0.6.1 lib/muflax/enumerable.rb
muflax-0.6.0 lib/muflax/enumerable.rb