Skip to content

Instantly share code, notes, and snippets.

@anselm-helbig
Last active June 6, 2016 10:38
Show Gist options
  • Save anselm-helbig/b87cca5edd095446f780bf6318a1eb5a to your computer and use it in GitHub Desktop.
Save anselm-helbig/b87cca5edd095446f780bf6318a1eb5a to your computer and use it in GitHub Desktop.
OO solution to diamond kata
require "forwardable"
class Diamond
class Canvas
def initialize(size)
@size = size
end
def []=(x, y, value)
lines[size - y][x + size] = value
end
def to_s
lines.join("\n")
end
private
attr_reader :size
def lines
@lines ||= Array.new(width) { " " * width }
end
def width
size * 2 + 1
end
end
class MirroredCanvas
extend Forwardable
def initialize(x_factor, y_factor, canvas)
@canvas = canvas
@x_factor = x_factor
@y_factor = y_factor
end
def []=(x, y, value)
canvas[x, y] = value
canvas[x * x_factor, y * y_factor] = value
end
def_delegator :canvas, :to_s
private
attr_reader :canvas, :x_factor, :y_factor
end
ORIGIN = "A"
def initialize(target)
@target = target
end
def to_s
draw
canvas.to_s
end
private
attr_reader :target
def draw
(ORIGIN..target).zip(0.upto(size), size.downto(0)).each do |letter, x, y|
canvas[x, y] = letter
end
end
def canvas
@canvas ||=
MirroredCanvas.new(
-1, 1,
MirroredCanvas.new(
1, -1,
Canvas.new(size)))
end
def size
@size ||= target.ord - ORIGIN.ord
end
end
puts Diamond.new(ARGV.fetch(0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment