Skip to content

Instantly share code, notes, and snippets.

@Ferdy89
Last active August 29, 2015 14:21
Show Gist options
  • Save Ferdy89/6336bfc682986114520d to your computer and use it in GitHub Desktop.
Save Ferdy89/6336bfc682986114520d to your computer and use it in GitHub Desktop.
Verbose calculator
class MyNum < Struct.new(:n)
NUMBERS = {
zero: 0,
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
}
[:plus, :minus, :by, :divide_by].each do |op|
define_method(op) do
MyOp.new(n, op)
end
end
alias to_i n
end
class MyOp < Struct.new(:n, :op)
OPERATIONS = {
plus: :+,
minus: :-,
by: :*,
divide_by: :/,
}
MyNum::NUMBERS.keys.each do |i|
define_method(i) do
res = n.send(OPERATIONS[op], MyNum::NUMBERS[i])
MyNum.new(res)
end
end
end
MyNum::NUMBERS.keys.each do |n|
define_method(n) do
MyNum.new(MyNum::NUMBERS[n])
end
end
raise unless one.plus.one.to_i == 2
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