Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Ractor#send
# File tmp/rubies/ruby-3.4.1/ractor.rb, line 599
def send(obj, move: false)
__builtin_cexpr! %q{
ractor_send(ec, RACTOR_PTR(self), obj, move)
}
end
Send a message to a Ractor’s incoming queue to be accepted by Ractor.receive.
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):
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.
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.
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.
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.
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:
r = Ractor.new {puts "Received: #{receive}"} s = 'message'.freeze r.send(s, move: true) s.inspect #=> "message", still available