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?

+4


source to share


5 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 

      

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 

      

+11


source


To add all digits from a number, you can use the following:

18.to_s.chars.map(&:to_i).reduce(:+)

      



It converts a number to a string, breaks it down into numbers, converts each to an integer, and concatenates everything together.

Works with numbers of any length.

+1


source


This is how I would do it:

any_number = 1234

# Ensure your input is at most a two digit number (might not be needed)
two_digit_number = any_number % 100                    #=> 34

# Calculate the final addition
total = two_digit_number / 10 + two_digit_number % 10  #=> 7

      

0


source


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)

      

0


source


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

-1


source







All Articles