Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Enumerable

Enumerable | 65

1.month # => 1 month
1.month.ago # => Mon Sep 24 23:57:04 -0500 2007
1.month.since(1.year.ago) # => Fri Nov 24 23:57:04 -0600 2006
The addition ofActiveSupport::Durationfixes many subtle problems with time calcu-
lations, because it stores durations as exact values (years, months, days, hours, min-
utes, and seconds). Prior to its addition, errors could easily accumulate, as some
duration functions assumed 30-day months and 365.25-day years.


  • Time#advance adds the specified (exact) values to the given time:
    t = Time.now # => Wed Oct 24 23:50:11 -0500 2007
    t.advance :days => 1 # => Thu Oct 25 23:50:11 -0500 2007
    t.advance :months => 1 # => Sat Nov 24 23:50:11 -0600 2007
    t.advance :years => 1 # => Fri Oct 24 23:50:11 -0500 2008

  • Convenient shorthand methods, listed below (all are instance methods ofTimethat
    take no arguments):
    — last_year andnext_year
    — last_month andnext_month
    — beginning_of_week (aliased asmonday andat_beginning_of_week) andnext_week
    — beginning_of_day(aliased asmidnight,at_midnight, andat_beginning_of_day) and
    end_of_day
    — beginning_of_month(alsoat_beginning_of_month) andend_of_month(alsoatend
    of_month)
    — beginning_of_quarter (at_beginning_of_quarter)
    — beginning_of_year (at_beginning_of_year)
    — yesterday,tomorrow


Enumerable core_ext/enumerable.rb



  • Enumerable#group_by groups the values into a hash based on the result of a block.
    (1..5).to_a.group_by {|x| x%3} # => {0=>[3], 1=>[1, 4], 2=>[2, 5]}

  • Enumerable#index_byindexes values based on the result of a block. It differs from
    group_by in that it only keeps one value per index key.
    (1..5).to_a.index_by {|x| x%3} # => {0=>3, 1=>4, 2=>5}

  • Enumerable#sumreturns the sum of the values (or the result of mapping the given block
    over the values, if a block is given). The optional first argument provides a value to use
    if the enumerable is empty.
    (1..5).to_a.sum # => 15
    (1..5).to_a.sum {|x| x ** 2} # => 55
    This makes statistical calculations easy:
    module Enumerable
    def mean
    (sum.to_f) / length
    end


def variance
m = mean
Free download pdf