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:
- Convert the integer to a string;
- Get the last character of the string;
- Convert the string back to integer;
- 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
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.