Skip to content

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

instance method

Ractor#send

(untyped obj, ?move: ::boolish) -> ::Ractor
ractor.send(msg, move: false) → self

Send a message to a Ractor’s incoming queue to be accepted by Ractor.receive.

Example
r = Ractor.new do
  value = Ractor.receive
  puts "Received #{value}"
end
r.send 'message'
# Prints: "Received: message"

The method is non-blocking (will return immediately even if the ractor is not ready to receive anything):

Example
r = Ractor.new {sleep(5)}
r.send('test')
puts "Sent successfully"
# Prints: "Sent successfully" immediately

An attempt to send to a ractor which already finished its execution will raise Ractor::ClosedError.

Example
r = Ractor.new {}
r.take
p r
# "#<Ractor:#6 (irb):23 terminated>"
r.send('test')
# Ractor::ClosedError (The incoming-port is already closed)

If close_incoming was called on the ractor, the method also raises Ractor::ClosedError.

Example
r =  Ractor.new do
  sleep(500)
  receive
end
r.close_incoming
r.send('test')
# Ractor::ClosedError (The incoming-port is already closed)
# The error is raised immediately, not when the ractor tries to receive

If the obj is unshareable, by default it will be copied into the receiving ractor by deep cloning. If move: true is passed, the object is moved into the receiving ractor and becomes inaccessible to the sender.

Example
r = Ractor.new {puts "Received: #{receive}"}
msg = 'message'
r.send(msg, move: true)
r.take
p msg

This prints:

Received: message
in `p': undefined method `inspect' for #<Ractor::MovedObject:0x000055c99b9b69b8>

All references to the object and its parts will become invalid to the sender.

Example
r = Ractor.new {puts "Received: #{receive}"}
s = 'message'
ary = [s]
copy = ary.dup
r.send(ary, move: true)

s.inspect
# Ractor::MovedError (can not send any methods to a moved object)
ary.class
# Ractor::MovedError (can not send any methods to a moved object)
copy.class
# => Array, it is different object
copy[0].inspect
# Ractor::MovedError (can not send any methods to a moved object)
# ...but its item was still a reference to `s`, which was moved

If the object is shareable, move: true has no effect on it:

Example
r = Ractor.new {puts "Received: #{receive}"}
s = 'message'.freeze
r.send(s, move: true)
s.inspect #=> "message", still available
See also #recv #take #receive_if #to_s also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0