Feature #8804
openONCE syntax
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.¶
Updated by andhapp (Anuj Dutta) over 11 years ago
Hello,
Do you have any use-cases to share for the new syntax?
Thanks.
Regards
Updated by trans (Thomas Sawyer) over 11 years 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
Updated by trans (Thomas Sawyer) over 11 years ago
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]
Updated by ko1 (Koichi Sasada) over 11 years 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 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
Updated by matz (Yukihiro Matsumoto) over 11 years 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.
Updated by Anonymous over 11 years 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
Updated by Eregon (Benoit Daloze) almost 4 years ago
- Related to Feature #17474: Interpreting constants at compile time added
Updated by hsbt (Hiroshi SHIBATA) 9 months ago
- Status changed from Open to Assigned