[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Question in factorial program
From:       Marc Chanliau <marc.chanliau () gmail ! com>
Date:       2017-07-27 14:04:55
Message-ID: 1E9E3E1B-B1AC-4E49-A40C-1FE3B78B2E55 () gmail ! com
[Download RAW message or body]

This is actually a pretty neat explanation. Thanks for taking the time. 

Sent from mobile device - Pardon possible typos!

> On Jul 26, 2017, at 11:12 PM, Matthew Kerwin <matthew@kerwin.net.au> wrote:
> 
> If anyone's still playing along,  #inject is also an alias for #reduce
> -- you may have heard of "MapReduce", it's one half of that --
> reducing an enumeration of values down to a single value, using a
> repeated operation.
> 
> The long form looks a bit like this:
> 
> ```
> [1,3,5].reduce { |subtotal, e| subtotal + e }
> 
> # or with an initial subtotal:
> [1,3,4].reduce(0) { |subtotal, e| subtotal + e }
> ```
> 
> (Similar effects can be achieved using #each_with_object)
> 
> To make it simpler, #reduce/#inject accepts a symbol as its final
> parameter, which is basically used like this:
> 
> ```
> # [1,3,5].reduce(:+)  =>
> [1,3,5].reduce { |memo, e| memo.__send__(:+, e) }
> ```
> 
> Further, there's Ruby's special `&foo` syntax that turns `foo` into a
> Proc object using its #to_proc method
> 
> Symbol#to_proc returns a Proc that is basically:
> 
> ```
> proc { |first, *rest| first.__send__(this_sym, *rest) }
> ```
> 
> So you could also write the inject/reduce code as:
> 
> ```
> [1,3,5].reduce(&:+)
> ```
> 
> It's pretty neat.  You can do dumb stuff like this:
> 
> ```
> class Integer
>  def absplus o
>    self.abs + o.abs
>  end
> end
> [1,-3,5].reduce :absplus   # => 9
> ```
> 
> Cheers
> -- 
>  Matthew Kerwin
>  http://matthew.kerwin.net.au/
> 
> Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic