--pgp-sign-Multipart_Wed_Jun__4_17:17:29_2008-1
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: quoted-printable

At Wed, 4 Jun 2008 03:38:48 +0900,
David Flanagan wrote:
> Akinori MUSHA wrote:
> > Hi,
> >
> > Earlier today I added a new instance method named `with_memo' to
> > Enumerable::Enumerator, but I'm not 100% sure if the name fits the
> > function.
> 
> What does the method do?  What's the use-case?

From rdoc:

    call-seq:
      e.with_memo(obj) {|(*args), memo_obj| ... }
      e.with_memo(obj)

    Iterates the given block for each element with an arbitrary
    object given, and returns the memo object.

    If no block is given, returns an enumerator.

For example:

    class Array
      def my_map
        return with_memo([]) {|i, memo| memo << yield(i) }

        # Instead of:
        ary = []
        each {|i| ary << yield(i) }
        return ary

        ## Using a throwaway variable within a block is fine, but
        ## initializing it beforehand and returning it afterwards
        ## outside the block is ugly.

        # Or:
        return inject([]) {|memo, i| memo << yield(i); memo }

        ## This is fine but a bit less comprehensive and awkward
        ## because you have to care about the return value when memo
        ## is constant here.
      end
    end


    a = [2,5,2,1,5,3,4,2,1,0]

    # Remove element duplicates:
    a.delete_if.with_memo({}) {|i, seen|
      if seen.key?(i)
        true
      else
        seen[i] = true
        false
      end
    }

    p a  # [2, 5, 1, 3, 4, 0]

    ## The point is `seen' is only seen in the block, and there is no
    ## leftover variable after the operation.
    ##
    ## Note that you cannot easily do the equivalent job with
    ## inject().


The method is for eliminating the typical need for a local variable to
accumulate into or look up on from within a block.

>                                                 And can't new methods
> like this wait 'till the Ruby 2.0 development branch opens up?  :-)

Is there any near-future plans for that?  I must agree that it is
important to have a policy for 1.9 that we all follow, but so long as
ruby 1.9 is the most active development series, you can't stop
improving it. ;)

-- 
Akinori MUSHA / http://akinori.org/

--pgp-sign-Multipart_Wed_Jun__4_17:17:29_2008-1
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (FreeBSD)

iEYEABECAAYFAkhGT5kACgkQkgvvx5/Z4e65hACdFM9gMgLbUbMdz003Q99Daie+
qp4AmQHrkoFhBEY/6CzlJsWoYGBzrMuS
2n
-----END PGP SIGNATURE-----

--pgp-sign-Multipart_Wed_Jun__4_17:17:29_2008-1--