I wanted to see graphically what my programme was doing so I wrote this automatic flowchart generator:
class Object
def log(previous_method)
if not DEBUGGING
return
end
repr = if self.class == Enumerator then self.to_a else self end
if [Array, String].include?(repr.class) and repr.length > 100
repr = repr.first(20) + [". . ."] + repr.last(20)
end
if previous_method.downcase == 'start'
self.tap {|x| puts """
#{repr}
"""}
else
self.tap {|x| puts """
|
| #{previous_method}
|
V
#{repr}
"""}
end
end
end
Some testcases:
class Integer
def is_digits_pow_sum?(exp)
self .log("start")
.digits .log("Digits")
.map{|x| x**exp} .log("Each digit to the power of #{exp}")
.sum .log("Sum")
.equal?(self) .log("Equals the start? (#{self})")
end
end
441.is_digits_pow_sum?(3)
Generates the flowchart:
441
|
| Digits
|
V
[4, 4, 1]
|
| Each digit to the power of 3
|
V
[64, 64, 1]
|
| Sum
|
V
129
|
| Equals the start? (441)
|
V
false
class String
def alpha_value
self .log("Start")
.chars .log("Split char by char")
.map(&:alphabet_position) .log("Map by position in the alphabet")
.sum .log("Sum")
end
end
"hellopeople".alpha_value
Gives the flowchart:
hellopeople
|
| Split char by char
|
V
["h", "e", "l", "l", "o", "p", "e", "o", "p", "l", "e"]
|
| Map by position in the alphabet
|
V
[8, 5, 12, 12, 15, 16, 5, 15, 16, 12, 5]
|
| Sum
|
V
121