Consider this Ruby code using Ractors. What will it print?
r = Ractor.new do (0...5).map { |i| i * 2 } end result = r.take puts result.inspect
Remember that Ractor.new runs the block in parallel and take receives the result.
The Ractor runs the block which returns an array of doubled numbers from 0 to 4. The take method receives this array, so the output is [0, 2, 4, 6, 8].
Choose the correct statement about Ruby Ractors.
Think about how Ractors achieve true parallelism safely.
Ractors do not share memory to avoid race conditions. They communicate only by passing messages, which makes them safe for parallel execution.
What error will this code produce when run?
r1 = Ractor.new do @counter = 0 @counter += 1 @counter end puts r1.take
Instance variables inside a Ractor are local to it.
The instance variable @counter is local to the Ractor and can be used normally. The code runs without error and outputs 1.
What will this Ruby code print?
r = Ractor.new do msg = Ractor.receive msg * 3 end r.send(7) puts r.take
Look at how the Ractor receives and processes the message.
The Ractor receives the number 7, multiplies it by 3, and returns 21. The take method prints 21.
Given this Ruby code using multiple Ractors, how many items will the final array contain?
ractors = (0...3).map do |i| Ractor.new(i) do |index| Array.new(index + 2) { index } end end results = ractors.map(&:take) final = results.flatten puts final.size
Count how many elements each Ractor creates and sum them.
The Ractors create arrays of sizes 2, 3, and 4 (because index goes 0,1,2). So total elements = 2 + 3 + 4 = 9. But index starts at 0, so arrays are of sizes 2,3,4 respectively. Actually, 0+2=2, 1+2=3, 2+2=4. So total is 2+3+4=9. The code prints 9.