rubyintegerdigit

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?


Solution

  • 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