Created
May 15, 2015 19:23
-
-
Save Ferdy89/14cc645d50b6ac8cf8bf to your computer and use it in GitHub Desktop.
Lazy verbose calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class VerboseCalculator < Struct.new(:stack) | |
NUMBERS = { | |
zero: 0, | |
one: 1, | |
two: 2, | |
three: 3, | |
four: 4, | |
five: 5, | |
six: 6, | |
seven: 7, | |
eight: 8, | |
nine: 9, | |
} | |
OPERATIONS = { | |
plus: :+, | |
minus: :-, | |
by: :*, | |
divide_by: :/, | |
} | |
def to_i | |
current_value = stack.first | |
stack.drop(1).each_slice(2) do |op, n| | |
current_value = current_value.send(op, n) | |
end | |
current_value | |
end | |
NUMBERS.merge(OPERATIONS).each do |k, v| | |
define_method(k) do | |
stack << v | |
self | |
end | |
end | |
end | |
VerboseCalculator::NUMBERS.each do |k, v| | |
define_method(k) { VerboseCalculator.new([v]) } | |
end | |
raise unless one.plus.one.to_i == 2 | |
raise unless one.plus.one.plus.two.to_i == 4 | |
raise unless two.minus.one.to_i == 1 | |
raise unless three.by.two.to_i == 6 | |
raise unless four.divide_by.two.to_i == 2 | |
puts 'Works!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment