Complete the code to create a new Ractor that prints 'Hello from Ractor!'.
r = Ractor.new { puts [1] }
r.takeThe code inside the Ractor block must be a string literal to print. Using single quotes correctly defines the string.
Complete the code to send a message 'ping' to the Ractor and receive a reply.
r = Ractor.new do msg = Ractor.receive Ractor.yield(msg + [1]) end r.send('ping') puts r.take
The Ractor receives a string and appends another string 'pong'. The string must be quoted.
Fix the error in the code to correctly pass data to the Ractor.
r = Ractor.new([1]) do |data| data * 2 end puts r.take
The Ractor.new method expects a single argument to pass to the block. It must be wrapped in an array to be passed as one argument.
Fill both blanks to create a Ractor that calculates squares of numbers and returns a hash.
numbers = [1, 2, 3] squares = Ractor.new(numbers) do |nums| nums.each_with_object([1]) do |n, h| h[n] = n [2] 2 end end puts squares.take
The method each_with_object needs a hash as the initial object, so use {}. To calculate squares, use the exponent operator **.
Fill all three blanks to create a Ractor that filters even numbers and sums them.
nums = [1, 2, 3, 4, 5, 6] r = Ractor.new(nums) do |list| evens = list.select { |num| num [1] 2 [2] 0 } evens.[3](:+) end puts r.take
To filter even numbers, use modulo % 2 == 0. To sum the numbers, use reduce(:+).