我写了一段代码,当传递给这个方法的数字中有一个重复的数字时返回false. no_repeat(2114567) #= false 以下是代码.我找不到它有什么问题.有任何建议,请改善这一点. def no_repeat(x) x = x.to_s.spl
no_repeat(2114567) #=> false
以下是代码.我找不到它有什么问题.有任何建议,请改善这一点.
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
false不返回函数,除非它是函数的最后一个表达式;明确地返回它.
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}
假
“11345′.each_char.each_cons(2).ANY? {| x,y | x == y}
真正
使用正则表达式(捕获组,反向引用)的替代方法:
def no_repeat(x) ! (/(.)\1/ === x.to_s) end
p11y使用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
