"once" methods

Hi,

I was reading PickAxe and came across the very cool concept of "once" methods, which are methods that only evaluate when first called, returning a cached value for subsequent calls.

Looking around a little on the Internet, I see a note that rolling this into Ruby's standard library was approved at some point, something that seems like a good idea to me. However, I can't immediately find where this functionality would be located. Google searches for "once" and "method" and "Ruby" understandably turn up a great many results that have nothing to do with what I'm looking for.

Has this been rolled into the standard library? If so, where?

Thanks in advance,
steve

Maybe #memoize.

This is usually called memoization, but I'm not aware of a standard library that handles it.

James Edward Gray II

···

On Sep 24, 2005, at 12:57 AM, Steven Arnold wrote:

Hi,

I was reading PickAxe and came across the very cool concept of "once" methods, which are methods that only evaluate when first called, returning a cached value for subsequent calls.

I looked at the RCR, I think once is something a little more low level
than memoize:

  a = nil
  x = "FOO"
  10.times do
    a = once { "#{x}" }
    x = "BAR"
  end
  p a #=> "FOO"

Akin to persistant locals:

  def x
    arr = []
    %a ||= 0
    2.times do
      arr << %a += 1
    end
    arr
  end

  x #=> [1, 2]
  x #=> [3, 4]

Hmm.. actaually this might help solve the whole ||= thing.

  module
    def module_info
      @module_info = once{ {} }
    end
  end

T.

http://raa.ruby-lang.org/project/memoize/

I havent yet tried it out, but if this doesn't work, it's not too hard to
implement.

···

On 9/24/05, James Edward Gray II <james@grayproductions.net> wrote:

On Sep 24, 2005, at 12:57 AM, Steven Arnold wrote:

> Hi,
>
> I was reading PickAxe and came across the very cool concept of
> "once" methods, which are methods that only evaluate when first
> called, returning a cached value for subsequent calls.

This is usually called memoization, but I'm not aware of a standard
library that handles it.

--
Rob