Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the rightmost digit from an Integer - Ruby

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?

like image 707
Zubatman Avatar asked Nov 26 '14 05:11

Zubatman


2 Answers

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 
like image 125
Santhosh Avatar answered Oct 17 '22 02:10

Santhosh


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.

like image 1
mbillard Avatar answered Oct 17 '22 02:10

mbillard