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

      

+3


source to share


3 answers


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

      

+6


source


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?

.

+1


source


If you want to know if a digit appears more than once in a number

x.to_s.chars - x.to_s.chars.uniq == 0

      

If you want to know if a digit is displayed sequentially in the number, you can try this

x.to_s.chars.each_cons(2).to_a.count{|array|array.uniq.length == 1} > 0

      

0


source







All Articles