Ruby program to count the number of digits in a number

Counting the number of digits: Here, we are going to learn how to count the number of in a given number in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 21, 2019

Counting the number of digits

Ruby does not provide you any predefined direct method through which you can find the number of digits in a number. Though one method can be implemented by converting the number into a string and then apply .length method to it. In that case, the expression will look like “number.to_s.length” but that requires conversion of number into a string. If you do not want to apply such type of method then you can go for the code given below.

Methods used:

  • puts: This method is a predefined method which is used to print a string on the console.
  • gets: The gets method is used to get a string from the user through the console.

Variables used:

  • num: This variable is storing the number which is provided by the user.
  • temp: This is acting as the temporary variable which is storing the value available in num.
  • count: This is acting as a counter variable. It is storing the number of digits available in num.

Ruby code to count the number of digits in a number

Ruby program to count the number of digits

puts "Enter the number:"


while (temp>0)

puts "#{num} has #{count} digits"


RUN 1:
Enter the number
89744 has 5 digits

RUN 2:
Enter the number
8171627331 has 10 digits

Code explanation:

You can observe in the above code that we have taken a variable count, which is behaving as a counter and counting the number of digits. The count is initialized by 0 and is incrementing when the condition mentioned with while loop is coming out to be true. The number is getting divided by 10 after every iteration. The code is not complex and is very easy to understand.

Ruby Basic Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.