How to get the rightmost digit from an Integer - Ruby
I am working on a program that requires me to read and check a number, but in doing so I need to take a two-digit integer (for example, we say 18) and add it 1 + 8. Now I have this work where I do conditional checking if it is greater than 10 and subtracts, but such an ugly solution in my opinion and wondered if there is a cleaner way to do this?
source to share
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
Use Integer # abs to handle negative numbers .
EDIT
Ruby 2.4 has an Integer # digits method . This will give you the numbers as an array, starting at unit space. And if you want to add numbers, you can use Enumerable # sum .
123.digits
# =>[3, 2, 1]
123.digits.first
# => 3
123.digits.sum
# => 6
source to share
For two-digit integers, there is at least another method we could use: Numeric#divmod
which returns the quotient and modulus in an array. And here's a look at the speed of the various approaches to sum up the numbers:
b = 18
n = 1_000_000
Benchmark.bmbm do |x|
x.report('to_s:') { n.times { b.to_s.chars.map(&:to_i).reduce(:+) }}
x.report('divmod:') { n.times { b.divmod(10).reduce(:+) }}
x.report('direct division:') { n.times { b/10 + b%10 } }
x.report('digits:') { n.times { a.digits.reduce(:+) } }
end
#####
user system total real
to_s: 0.750000 0.000000 0.750000 ( 0.750700)
divmod: 0.150000 0.000000 0.150000 ( 0.153516)
direct division: 0.080000 0.000000 0.080000 ( 0.076697)
digits: 0.560000 0.020000 0.580000 ( 0.574687)
source to share
def digits_sum(number,n)
number_array=number.to_s.chars
n=[n,number_array.length].min
number_array.slice(-n,n).map {|c| c.to_i }.reduce(:+) || 0
end
this method returns the sum of the N right digits.
digits_sum 123456789,5 => 35
digits_sum 123456789,2 => 17
This will work if you give N more than the number length, but won't work if you give a negative count
source to share