Project

General

Profile

Actions

Feature #8804

open

ONCE syntax

Added by ko1 (Koichi Sasada) over 11 years ago. Updated 9 months ago.

Status:
Assigned
Target version:
-
[ruby-core:56753]

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.


Related issues 2 (1 open1 closed)

Related to Ruby master - Feature #9037: Memoization of "anonymous constants"ClosedActions
Related to Ruby master - Feature #17474: Interpreting constants at compile timeOpenActions

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

Actions #7

Updated by naruse (Yui NARUSE) almost 7 years ago

  • Target version deleted (2.6)
Actions #8

Updated by Eregon (Benoit Daloze) almost 5 years ago

  • Description updated (diff)
Actions #9

Updated by Eregon (Benoit Daloze) almost 4 years ago

  • Related to Feature #17474: Interpreting constants at compile time added
Actions #10

Updated by hsbt (Hiroshi SHIBATA) 9 months ago

  • Status changed from Open to Assigned
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0