Skip to content

Instantly share code, notes, and snippets.

@dskecse
Created December 26, 2025 14:28
Show Gist options
  • Select an option

  • Save dskecse/93aed68312379dd24c3365aaa7557968 to your computer and use it in GitHub Desktop.

Select an option

Save dskecse/93aed68312379dd24c3365aaa7557968 to your computer and use it in GitHub Desktop.
Ruby 4.0 Ractor push type (send/receive) communication with Ractor::Port
# frozen_string_literal: true
p RACTOR_COUNT: Ractor.count # => 1
p IS_MAIN_RACTOR: Ractor.main? # => true
p Ractor.main # => #<Ractor:#1 running>
port = Ractor::Port.new
p port # => #<Ractor::Port to:#1 id:1>
Ractor.new(port) do |port|
p RACTOR_COUNT: Ractor.count # => 2
p IS_MAIN_RACTOR: Ractor.main? # => false
p RACTOR: Ractor.current # => #<Ractor:#2 ractor_port.rb:9 running>
p PORT: port # => #<Ractor::Port to:#1 id:1>
p DEFAULT_PORT: Ractor.current.default_port # => #<Ractor::Port to:#2 id:0>
p "Sending to port #{port}"
port.send 42
end
p PRE_RECEIVE_RACTOR_COUNT: Ractor.count # => 2
p "Receiving from port #{port}"
p port.receive
p FINAL_RACTOR_COUNT: Ractor.count # => 1
@dskecse
Copy link
Author

dskecse commented Dec 26, 2025

$ ruby example.rb
{RACTOR_COUNT: 1}
{IS_MAIN_RACTOR: true}
#<Ractor:#1 running>
#<Ractor::Port to:#1 id:1>
ractor_port.rb:9: warning: Ractor API is experimental and may change in future versions of Ruby.
{PRE_RECEIVE_RACTOR_COUNT: 2}
"Receiving from port #<Ractor::Port:0x0000000123186838>"
{RACTOR_COUNT: 2}
{IS_MAIN_RACTOR: false}
{RACTOR: #<Ractor:#2 example.rb:9 running>}
{PORT: #<Ractor::Port to:#1 id:1>}
{DEFAULT_PORT: #<Ractor::Port to:#2 id:0>}
"Sending to port #<Ractor::Port:0x0000000123186838>"
42
{FINAL_RACTOR_COUNT: 1}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment