How to Get the Last Digit of an Integer in Ruby?

Getting the last digit of a Ruby integer

In Ruby, you can get the last digit of an integer in the following ways:

Using Numeric#remainder()

You can use the Numeric#remainder() method to get the last digit of an integer, for example, like so:

def last_digit(num)
    num.remainder(10)
end

puts last_digit(0) #=> 0
puts last_digit(1234) #=> 4
puts last_digit(-1234) #=> -4

Using the Numeric#remainder() method is equivalent to doing the following:

def last_digit(num)
    num - (10 * (num.to_f / 10).truncate)
end

puts last_digit(0) #=> 0
puts last_digit(1234) #=> 4
puts last_digit(-1234) #=> -4

Converting the number to float (using Integer#to_f) is important, as otherwise Ruby would round the result of division.

This works in the following way:

# num = 1234

# last_digit = 1234 - (10 * (1234 / 10).truncate)
# last_digit = 1234 - (10 * (123.4).truncate)
# last_digit = 1234 - (10 * 123)
# last_digit = 1234 - 1230
# last_digit = 4

Converting to String and Returning Last Character

You could do the following:

  1. Convert the integer to a string;
  2. Get the last character of the string;
  3. Convert the string back to integer;
  4. Add negative sign to the last digit if integer was negative.
def last_digit(num)
    num_str = num.to_s
    last_char = num_str[-1]
    last_digit_unsigned = last_char.to_i

    (num < 0) ? -last_digit_unsigned : last_digit_unsigned
end

puts last_digit(0) #=> 0
puts last_digit(1234) #=> 4
puts last_digit(-1234) #=> -4

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.