How can I duplicate numbers in Ruby using an if statement?

更新于
2026-10-09 19:51:36
2阅读来源:SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计328个文字,预计阅读时间需要2分钟。

How can I duplicate numbers in Ruby using an if statement?

我编写了一段代码,当传递给这个方法的数字中有重复的数字时,返回false。no_repeat(2, 1, 4, 5, 6, 7) 返回 false

我写了一段代码,当传递给这个方法的数字中有一个重复的数字时返回false.

no_repeat(2114567) #=> false

以下是代码.我找不到它有什么问题.有任何建议,请改善这一点.

How can I duplicate numbers in Ruby using an if statement?

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

本文共计328个文字,预计阅读时间需要2分钟。

How can I duplicate numbers in Ruby using an if statement?

我编写了一段代码,当传递给这个方法的数字中有重复的数字时,返回false。no_repeat(2, 1, 4, 5, 6, 7) 返回 false

我写了一段代码,当传递给这个方法的数字中有一个重复的数字时返回false.

no_repeat(2114567) #=> false

以下是代码.我找不到它有什么问题.有任何建议,请改善这一点.

How can I duplicate numbers in Ruby using an if statement?

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