"once" methods

S

Steven Arnold

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
 
J

James Edward Gray II

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.

James Edward Gray II
 
T

Trans

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.
 
R

Rob Rypka

------=_Part_19214_31744150.1127575604797
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top