I coded up a solution to the narcissistic numbers kata on codewars.
After writing a single function, I extracted two helper functions in order to keep my line count at a maximum of 5 lines (Sandi Metz' Rules For Developers).
This resulted in 3 functions:
def digits(number)
number
.to_s
.chars
.map(&:to_i)
end
def checksum(digits, exp)
digits
.map { |d| d**exp }
.reduce(:+)
end
def narcissistic?(number)
digits = digits(number)
exp = digits.length
checksum = checksum(digits, exp)
checksum == number
end
Now, I would like to pretend that this code should be added to a larger real-world project. My question is how this should be idiomatically done in Ruby.
Generally speaking, I have two requirements:
- The code should be somehow namespaced (considering a real-world project).
- It should be clear that
narcissistic?
is the public API function - being on a higher level, while the other two functionsdigits
andchecksum
are on a lower level of abstraction.
My reasoning so far is: This code does not really need OOP. But in Ruby the only way to get something into a namespace is by creating a Class
or a Module
.
Probably, a Module
would be a better choice? Still, I am not sure whether I should prefer:
module MathUtils::NarcissisticNumbers
def self.narcissistic?(number)
...
end
private
...
end
vs
module MathUtils::NarcissisticNumbers
def narcissistic?(number)
...
end
private
...
end
How would you bring in this code into a Ruby project? Please, if you know a best-practices solution, let me know! :)
Any other pointers would be highly appreciated as well.