I am working on a program that requires me to read in and validate a number, but in doing so I need to take a two digit integer (for example we'll say 18) and add it 1 + 8. Now I have it working where I do a conditional check if it is greater than 10 and subtract, but that's kind of an ugly solution in my opinion and was wondering if there is a cleaner way of doing it?
You can use the modulo operator n % 10
, to get the rightmost digit. For example:
18 % 10
# => 8
9 % 10
# => 9
0 % 10
# => 0
(-123).abs % 10
# => 3
To handle negative numbers, use Integer#abs.
EDIT
Ruby 2.4 has a Integer#digits method. It will give you the digits as an array, starting from unit's place. And if you want to add the digits, you can use Enumerable#sum.
123.digits
# =>[3, 2, 1]
123.digits.first
# => 3
123.digits.sum
# => 6
To add all digits from a number, you can use the following:
18.to_s.chars.map(&:to_i).reduce(:+)
It transforms the number into a string, splits it into digits, transforms each into an integer and adds them all together.
Works with numbers of any length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With