Project

General

Profile

Actions

Feature #8804

open

ONCE syntax

Added by ko1 (Koichi Sasada) over 10 years ago. Updated 22 days 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
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0