Ruby中如何将重复数字通过if子句转换成长尾词?

2026-04-11 15:351阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

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

Ruby中如何将重复数字通过if子句转换成长尾词?

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

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

no_repeat(2114567) #=> false

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

Ruby中如何将重复数字通过if子句转换成长尾词?

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分钟。

Ruby中如何将重复数字通过if子句转换成长尾词?

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

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

no_repeat(2114567) #=> false

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

Ruby中如何将重复数字通过if子句转换成长尾词?

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