0
0
Rubyprogramming~7 mins

Ractor for true parallelism in Ruby

Choose your learning style9 modes available
Introduction

Ractor lets Ruby run code truly at the same time on multiple CPU cores. This helps programs run faster by doing many things together.

When you want to speed up a program by doing tasks at the same time.
When you have heavy calculations that can be split into parts.
When you want to avoid waiting for one task to finish before starting another.
When you want to use multiple CPU cores efficiently.
When you want to keep your program responsive while doing background work.
Syntax
Ruby
ractor = Ractor.new do
  # code to run in parallel
  result = some_work
  Ractor.yield(result) # send result back
end

value = ractor.take # get result from ractor

Ractor.new creates a new parallel task.

Use Ractor.yield to send data back from inside the ractor.

Examples
This example creates a ractor that calculates 5 times 5 and sends back 25.
Ruby
ractor = Ractor.new do
  5 * 5
end

result = ractor.take
puts result
This ractor sums numbers from 1 to 10 and returns the total.
Ruby
ractor = Ractor.new do
  sum = 0
  (1..10).each { |n| sum += n }
  sum
end

puts ractor.take
This example shows how to send a message back using Ractor.yield.
Ruby
ractor = Ractor.new do
  Ractor.yield("Hello from ractor")
end

message = ractor.take
puts message
Sample Program

This program shows how to use a ractor to calculate squares of numbers from 1 to 5 in parallel. The main program prints messages before and after getting the result.

Ruby
puts "Main program starts"

# Create a ractor to calculate squares of numbers
square_ractor = Ractor.new do
  squares = []
  (1..5).each do |number|
    squares << number * number
  end
  squares
end

# Main program continues while ractor works
puts "Doing other work in main thread..."

# Get result from ractor
result = square_ractor.take
puts "Squares calculated in ractor: #{result}"

puts "Main program ends"
OutputSuccess
Important Notes

Time complexity depends on the task inside the ractor, but using ractors can speed up multi-core processing.

Space complexity includes the memory used by the ractor and its data.

Common mistake: Trying to share mutable objects between ractors causes errors. Use message passing instead.

Use ractors when you need true parallelism. For simple concurrency, threads might be enough.

Summary

Ractors let Ruby run code truly in parallel on multiple CPU cores.

Use Ractor.new to create a parallel task and Ractor.yield or take to communicate.

Ractors help speed up programs by doing work at the same time safely.