Assigned reading for my program is The Well Grounded Rubyist, and having come to the 4th chapter, I decided to try making some modules. I wrote a Calculator class with some basic calculation methods abstracted to a class method_missing method:
I didn't understand how class methods worked until the WGR explained that they worked on the class object itself, while instance methods worked individually, on single instances of the class. This seemed like a good time to try out class methods, as I had written them before but didn't understand how they worked, and a calculator seemed like an especially appropriate use.
Now to add the mixin module, which I already included in the Calculator class, but using the
extend keyword (thanks to
the article "Include vs Extend in Ruby"):
median method got a bit complicated, but I had a very specific idea of what I wanted it to return in a variety of cases.
Plus I jumped on the chance to do some more recursion! Output:
Just as expected. Mainly the issue I had with this was when running into NoMethodErrors when initially using
include rather than
extend. Overall, modules are clearly super useful and I'll definitely expect to use them in the future.