Repeated digit in ruby using if condition
I wrote a piece of code to return false
when a digit is repeated in a number passed to a method like this.
no_repeat(2114567) #=> false
Below is the code. I couldn't find what was wrong with him. Any suggestions for improving this please.
def no_repeat(x)
x = x.to_s.split('')
i = 0
while i < x.length
if x[i].to_s == x[i + 1]
false
end
i += 1
end
true
end
no_repeat(2114567) #=> true
source to share
false
does not return a function if it is not the last function expression; explicitly return it.
def no_repeat(x)
x = x.to_s.split('')
i = 0
while i < x.length
if x[i].to_s == x[i + 1]
return false # <--------
end
i += 1
end
true
end
no_repeat(2114567) # => false
no_repeat(1234) # => true
'12345'.each_char.each_cons (2). Any? {| x, y | x == y} false "11345'.each_char.each_cons (2) .any? {| x, y | x == y} true
Alternative using regular expression (capturing group, backlink):
def no_repeat(x)
! (/(.)\1/ === x.to_s)
end
Another alternative suggested by p11y using each_cons
:
'12345'.each_char.each_cons(2).none? { |x, y| x == y }
# => true
'11345'.each_char.each_cons(2).none? { |x, y| x == y }
# => false
'12345'.each_char.each_cons(2).all? { |x, y| x != y }
# => true
'11345'.each_char.each_cons(2).all? { |x, y| x != y }
# => false
source to share
def no_repeat(n)
s = n.to_s
s.size == s.squeeze.size
end
no_repeat(2114567) #=> false
no_repeat(-2114567) #=> false
no_repeat(2141567) #=> true
I suggest you change the method so that it returns true
when there are duplicate numbers and renames it to something like repeated_digits?
.
source to share