Feature #8804

ONCE syntax

Added by Koichi Sasada 8 months ago. Updated 8 months ago.

[ruby-core:56753]
Status:Open
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:syntax
Target version:next minor

Description

How about to introduce ONCE{...} syntax which do block only once and return the first value?

  • It is similar of BEGIN{} and END{}.
  • General syntax of /reg/o.

simulation code

ONCECACHE = {}
ONCE
MUTEX = Mutex.new
def ONCE(&b)
raise unless blockgiven?
ONCE
MUTEX.synchronize{
key = caller(3, 1)[0]
if value = ONCECACHE[key]
value
else
ONCE
CACHE[key] = yield
end
}
end

3.times{|i|
p ONCE{
i #=> every time 0
}
}
##

Note that this code doesn't work if two or more ONCE{} are available in one line.


Related issues

Related to ruby-trunk - Feature #9037: Memoization of "anonymous constants" Open 10/20/2013

History

#1 Updated by Anuj Dutta 8 months ago

Hello,

Do you have any use-cases to share for the new syntax?

Thanks.

Regards

#2 Updated by Thomas Sawyer 8 months ago

A use case is memoization. Instead of

def q
@q ||= (...some long calc...)
end

You could do

def q
ONCE { ...some long calc... }
end

#3 Updated by Thomas Sawyer 8 months ago

Also, can it take an optional key argument?

def ONCE(k=nil,&b)
raise unless blockgiven?
ONCE
MUTEX.synchronize{
key = k || caller(3, 1)[0]

#4 Updated by Koichi Sasada 8 months ago

(2013/08/20 19:30), trans (Thomas Sawyer) wrote:

Also, can it take an optional key argument?

def ONCE(k=nil,&b)
raise unless blockgiven?
ONCE
MUTEX.synchronize{
key = k || caller(3, 1)[0]

I assume that ONCE is keyword like BEGIN{} and END{}.
And key will be a special key provided by compiler.

Completely same feature as /#{...}/o.

--
// SASADA Koichi at atdot dot net

#5 Updated by Yukihiro Matsumoto 8 months ago

  • Status changed from Open to Rejected

I don't see any major use-case for the function.
Reopen if you (or anyone else) have.

Matz.

#6 Updated by Charlie Somerville 8 months ago

  • Status changed from Rejected to Open

matz: Here's some code I wrote recently that would benefit from ONCE:

https://github.com/charliesome/better_errors/blob/master/lib/better_errors/stack_frame.rb#L30-42

Also available in: Atom PDF