Protocol Errors :: 0x22
You've built a "Treasure Map" example program to teach a friend basic coding concepts. It's simple enough... it displays a text based grid for a map of a certain size, and then picks a random place where "X marks the spot" that the treasure is at.
- - - - -
- - - - -
- - - - -
- X - - -
- - - - -
The first few times you run the program, it works fine. Then on one of the test runs, you get weird output that isn't what you'd expect, even though the program doesn't crash.
- - - - -
- - - - -
- - - - -
- - - - - X
- - - - -
You run it a few more times just for good measure, and then things get even worse... it appears that there's a Null Error lurking in the code as well, and the program does crash when it hits that issue, without even printing out the map.
map.rb:13:in 'Map#mark': undefined method '[]=' for nil (NoMethodError)
@grid[point.y][point.x] = "X"
^^^^^^^^^^^
from map.rb:25:in '<main>'
Your bug hunting powers have been getting stronger and stronger lately, so you'll undoubtedly be able to figure out what's going wrong here.
All it takes is some careful code reading.
Review the code sample below to identify the root cause for why the program intermittently fails, and then describe how you'd fix it.
Point = Data.define(:x, :y)
class Map
def initialize(size)
@size = size
@grid = @size.times.map { Array.new(@size, "-") }
end
attr_reader :size
def mark(point)
@grid[point.y][point.x] = "X"
end
def to_s
@grid.map { |row| row.join(" ") }.join("\n")
end
end
## build a 5x5 map
map = Map.new(5)
## Hide a treasure in a random location on the map
map.mark(Point[rand(1..map.size), rand(1..map.size)])
puts map
You can preorder now to be among the first to gain access when it is released.