Skip to content

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

class method

Ractor.receive

Ractor.receive → msg

Receive a message from the incoming port of the current ractor (which was sent there by send from another ractor).

Example
r = Ractor.new do
  v1 = Ractor.receive
  puts "Received: #{v1}"
end
r.send('message1')
r.take
# Here will be printed: "Received: message1"

Alternatively, the private instance method receive may be used:

Example
r = Ractor.new do
  v1 = receive
  puts "Received: #{v1}"
end
r.send('message1')
r.take
# This prints: "Received: message1"

The method blocks if the queue is empty.

Example
r = Ractor.new do
  puts "Before first receive"
  v1 = Ractor.receive
  puts "Received: #{v1}"
  v2 = Ractor.receive
  puts "Received: #{v2}"
end
wait
puts "Still not received"
r.send('message1')
wait
puts "Still received only one"
r.send('message2')
r.take

Output:

Before first receive
Still not received
Received: message1
Still received only one
Received: message2

If close_incoming was called on the ractor, the method raises Ractor::ClosedError if there are no more messages in the incoming queue:

Example
Ractor.new do
  close_incoming
  receive
end
wait
# in `receive': The incoming port is already closed => #<Ractor:#2 test.rb:1 running> (Ractor::ClosedError)
See also #receive .new .receive_if .make_shareable also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0