ruby picture

RCR 273: Enumerable#inject_with

Submitted by ummaycoc (Wed Aug 04 11:08:45 UTC 2004)

Abstract

Just lets you inject with any method that takes a block...

Problem

Blocks are everywhere. Why not inject with anything?

Proposal

I propose adding an inject_with method to Enumerable. This way, things that might not actually be `injectable' can be...

Analysis

This is simple. No clue what to put here.

Implementation

module Enumerable
  def Enumerable.inject_with(object, sym, id, *args)
    object.send(sym, *args) {|*values|
      id = yield id, *values
    }
    id
  end
end
ruby picture
Comments Current voting

Can you give an example or two? I'm not getting what this would do (simple or not :-)

-- David Black


I guess you should use 'enumerator' which is bundled with 1.8.

  object.to_enum(method).inject(init){....}

Using enumerator, you can enumerate over any method, not just inject.

--matz.

For what it can do - this is what I used it for:

  ifile, idir = *[:file?, :directory?].map {|sym|
    Proc.new {|root| inject_with(Find, :find, [], root) {|arr, path|
      FileTest.send(sym, path) ? arr << path : arr
    }}
  }
-- i.e. make procs to find all files and all directories using find. (simpler way to do that?) but it just seemed like a nice add on - but apparently enumerator can work. Is there documentation for enumerator somewhere in English?


You can find enumerator.txt in the ext/enumerator directory in the distribution archive.

--matz.


Strongly opposed 0
Opposed 5
Neutral 0
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .