# 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

```=begin
Ruby program to count the number of digits
=end

puts "Enter the number:"
num=gets.chomp.to_i

temp=num
count=0

while (temp>0)
count+=1
temp=temp/10
end

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

Output

```RUN 1:
Enter the number
89744
89744 has 5 digits

RUN 2:
Enter the number
8171627331
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.

TOP Interview Coding Problems/Challenges

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates