Ruby

## Day 12 of 30 - Ruby Coding Challenge - Repdigit Number Algorithm in a more Ruby Way Hey!

This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series

This post will be really short because Ruby, fortunately, provides us a really good way to solve the Repdigit Algorithm

## #1 Repdigit Algorithm Version 1

In this solution we’re going to take the following steps:

Step 1

• given a number, we’ll convert it into a String
``````number.to_s
``````

Step 2

• then we can use the method squeeze, which keeps only the unique digits\
``````number.to_s.squeeze
``````

Step 3

• now we validate if the remainder length of the array is 1
``````number.to_s.squeeze.length == 1
``````

The complete code would be:

``````def is_repdigit(number)
number.to_s.squeeze.length == 1
end

puts is_repdigit(777) # true
puts is_repdigit(774) # false
puts is_repdigit(555555) # true
puts is_repdigit(456555) # false
``````

Pretty simple, isn’t it? :)

## #2 Repdigit Algorithm Version 2

Another way to solve this problem is manipulating chars in Ruby

Step 1

• getting the chars from the String
``````number.to_s.chars
``````

Step 2

• getting the unique chars from the String
``````number.to_s.chars.uniq
``````

Step 3

• Validating if the length of the array is 1
``````number.to_s.chars.uniq.length == 1
``````

The complete code would be:

``````def is_repdigit(number)
number.to_s.chars.uniq.length == 1
end

puts is_repdigit(777) # true
puts is_repdigit(774) # false
puts is_repdigit(555555) # true
puts is_repdigit(456555) # false
``````

Amazing! Ruby allows us to solve the problem in a really beautiful and straightforward way 😃

That’s it! I hope you liked it and see you in the next challenge : )

Don’t forget to come by and say hi Alex