Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Ractor.select

Ractor.select(*ractors, [yield_value:, move: false]) → [ractor or symbol, obj]

Waits for the first ractor to have something in its outgoing port, reads from this ractor, and returns that ractor and the object received.

Example
r1 = Ractor.new {Ractor.yield 'from 1'}
r2 = Ractor.new {Ractor.yield 'from 2'}

r, obj = Ractor.select(r1, r2)

puts "received #{obj.inspect} from #{r.inspect}"
# Prints: received "from 1" from #<Ractor:#2 test.rb:1 running>

If one of the given ractors is the current ractor, and it would be selected, r will contain :receive symbol instead of the ractor object.

Example
r1 = Ractor.new(Ractor.current) do |main|
  main.send 'to main'
  Ractor.yield 'from 1'
end
r2 = Ractor.new do
  Ractor.yield 'from 2'
end

r, obj = Ractor.select(r1, r2, Ractor.current)
puts "received #{obj.inspect} from #{r.inspect}"
# Prints: received "to main" from :receive

If yield_value is provided, that value may be yielded if another Ractor is calling take. In this case, the pair [:yield, nil] would be returned:

Example
r1 = Ractor.new(Ractor.current) do |main|
  puts "Received from main: #{main.take}"
end

puts "Trying to select"
r, obj = Ractor.select(r1, Ractor.current, yield_value: 123)
wait
puts "Received #{obj.inspect} from #{r.inspect}"

This will print:

Trying to select
Received from main: 123
Received nil from :yield

move boolean flag defines whether yielded value should be copied (default) or moved.

See also .recv .shareable? .receive_if .yield also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0