为什么我在这个函数的字符串中找不到`" az"`?

时间:2015-08-15 17:52:48

标签: ruby

我想知道"a"之后"z""a"是否在一个字符串中。我想了解为什么这不起作用:

def nearby_az(string)
  i = 0
  while i < string.length 
    if string[i] == "a" && string[i+1] == "z"
      return true
    else
      return false
    end 
    i += 1
  end 
end

我意识到有一种简单的方法可以实现这一点。我不是在寻找另一种解决方案。

2 个答案:

答案 0 :(得分:5)

此代码只会找到&#34; az&#34;如果它在一开始。否则它将return false。推迟return false直到你走完整个字符串。

def nearby_az(string)

  i = 0
  while i < string.length -1  
    return true if string[i] == "a" && string[i+1] == "z"

    i += 1
  end 
  # we can only reach this line if the loop above does not return.
  # if it doesn't, then the substring we seek is not in the input.
  return false 
end

nearby_az('baz') # => true

答案 1 :(得分:4)

@Segio Tulentsev&#39;答案解释了为什么你的坏了。

如果您有兴趣

,这是简短的实施
def nearby_az(str)
  !! str =~ /a(?=z)/i
end
相关问题