Skip to content
class method · added in Ruby 3.4

Ractor.store_if_absent

[A] (::Symbol) { (nil) -> A } -> A
Ractor.store_if_absent(key){ init_block }

If the corresponding ractor-local value is not set, yields a value with init_block and stores the value in a thread-safe manner. This method returns the stored value.

Example
(1..10).map{
  Thread.new(it){|i|
    Ractor.store_if_absent(:s){ f(); i }
    #=> return stored value of key :s
  }
}.map(&:value).uniq.size #=> 1 and f() is called only once

Ruby version changes

  1. 3.4
    • Ractor.store_if_absent(key){ init } is added to initialize ractor local variables in thread-safety. [Feature #20875]