Came across an interesting code challenge on Code Wars a while back. It involved defining methods in a way to be able to type mathematical operations verbally, i.e.
one plus one which would return
I pondered over this for a while, and on a flight back from San Francisco came up with a neat solution and even learned a couple interesting things about metaprogramming.
I started with defining
one. I know that I’ll want to potentially pass an argument to
one. If I don’t have an argument, I’ll just want to return the integer
1. Simple enough. I can just give my method definition argument a default value of
nil, check whether I have an operator, and if I don’t, simply return the integer
1 2 3 4 5 6 7
Ok, so what should happen when I get an operator? I decided to find a way to implement