Skip to content

Instantly share code, notes, and snippets.

@kolo
Created May 30, 2016 12:05
Show Gist options
  • Save kolo/d13871c59ea15b49dab02f78e117b936 to your computer and use it in GitHub Desktop.
Save kolo/d13871c59ea15b49dab02f78e117b936 to your computer and use it in GitHub Desktop.
"Functional" approach to solve diamond kata
class Diamond
STARTING_CHARACTER = "A"
def initialize(letter)
@letter = letter
end
def to_s
lines.join("\n")
end
private
attr_reader :letter
def lines
go = ->(t, ch) {
t = t.push(spacify(line, ch)).unshift(spacify(line, ch))
if ch == STARTING_CHARACTER
t
else
go[t, prec(ch)]
end
}
go[[spacify(line, letter)], prec(letter)]
end
def line
go = ->(str, ch) {
str = ch + str + ch
if ch == letter
str
else
go[str, ch.succ]
end
}
go[STARTING_CHARACTER, STARTING_CHARACTER.succ]
end
def spacify(str, ch)
str.gsub(/[^#{ch}]/, " ")
end
def prec(ch)
(ch.ord - 1).chr
end
end
puts Diamond.new("D")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment