Feature #8804
open
Added by ko1 (Koichi Sasada) over 11 years ago.
Updated 8 months ago.
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¶
ONCE_CACHE = {}
ONCE_MUTEX = Mutex.new
def ONCE(&b)
raise unless block_given?
ONCE_MUTEX.synchronize{
key = caller(3, 1)[0]
if value = ONCE_CACHE[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.¶
Hello,
Do you have any use-cases to share for the new syntax?
Thanks.
Regards
A use case is memoization. Instead of
def q
@q ||= (...some long calc...)
end
You could do
def q
ONCE { ...some long calc... }
end
Also, can it take an optional key argument?
def ONCE(k=nil,&b)
raise unless block_given?
ONCE_MUTEX.synchronize{
key = k || caller(3, 1)[0]
(2013/08/20 19:30), trans (Thomas Sawyer) wrote:
Also, can it take an optional key argument?
def ONCE(k=nil,&b)
raise unless block_given?
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
- 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.
- Status changed from Rejected to Open
- Target version deleted (
2.6)
- Description updated (diff)
- Related to Feature #17474: Interpreting constants at compile time added
- Status changed from Open to Assigned
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0