Project

General

Profile

Actions

Feature #21518

open

Statistical helpers to `Enumerable`

Added by Amitleshed (Amit Leshed) 4 days ago. Updated 1 day ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:122842]

Description

Summary

I'd like to add two statistical helpers to Enumerable:

  • Enumerable#average (arithmetic mean)
  • Enumerable#median

Both are small, well-defined operations that many Rubyists re-implement in apps and gems. Providing them in core avoids repeated, ad-hoc code and aligns with Enumerable#sum, which Ruby already ships.

Motivation

  • These are among the most common “roll-your-own” helpers for arrays/ranges of numbers.
  • They are conceptually simple, universally useful beyond web/Rails.
  • Similar to sum, they’re primitives for quick data analysis, ETL scripts, CLI tooling, etc.
  • Including them encourages consistent semantics (what to do with empty sets, mixed numerics, etc.).

Proposed API & Semantics

Enumerable#average -> Float or nil
Enumerable#median  -> Numeric or nil
[1, 2, 3, 4].average      # => 2.5
(1..4).average            # => 2.5
[].average                # => nil

[1, 3, 2].median          # => 2
[1, 2, 3, 10].median      # => 2.5
(1..6).median             # => 3.5
[].median                 # => nil

Ruby implementation

module Enumerable
  def average
    count = 0
    total = 0.0
    each do |x|
      raise TypeError, "non-numeric value for average" unless x.is_a?(Numeric)
      total += x
      count += 1
    end
    count.zero? ? nil : total / count
  end

  def median
    arr = to_a
    return nil if arr.empty?
    arr.each { |x| raise TypeError, "non-numeric value for median" unless x.is_a?(Numeric) }
    arr.sort!
    mid = arr.length / 2
    arr.length.odd? ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2.0
  end
end

Upon approval I'm more than willing to implement spec and code in C.


Related issues 4 (1 open3 closed)

Related to Ruby - Feature #2321: [PATCH] Array Module sum and mean featuresRejected11/01/2009Actions
Related to Ruby - Feature #18057: Introduce Array#meanOpenActions
Related to Ruby - Feature #10228: Statistics moduleFeedback09/11/2014Actions
Related to Ruby - Feature #12222: Introducing basic statistics methods for Enumerable (and optimized implementation for Array)Closedakr (Akira Tanaka)Actions
Actions

Also available in: Atom PDF

Like1
Like1Like0Like1Like0Like0Like0Like0Like0