Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method · added in Ruby 3.4

Ractor.store_if_absent

(::Symbol) { () -> untyped } -> untyped
Ractor.store_if_absent(key){ init_block }

If the correponding value is not set, yield a value with init_block and store the value in thread-safe manner. This method returns corresponding 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]

See also .shareable? .yield .select #<< also in 4.1 · 4.0