使用if子句在ruby中重复数字
发布时间:2020-12-17 01:33:59 所属栏目:百科 来源:网络整理
导读:我写了一段代码,当传递给这个方法的数字中有一个重复的数字时返回false. 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.
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} 使用正则表达式(捕获组,反向引用)的替代方法: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |