为什么我得到这个错误:TrueClass(NoMethodError)

时间:2015-02-08 18:50:49

标签: ruby

我正在尝试找到一个字符a,然后在字符串中找到一个字符z 3或更少字符,这是我的代码:

def nearby_az(string)
  ind1 = string.index(?a)
  while ind1 != nil
    return ((ind2=string.index(?z,ind1)!=nil) and ((ind2-ind1) <= 3))  #if there is a z and ind bt a and z is
    #less than or equal to 3 then return true
    ind1 = string.index(?a,ind1)
  end
  return false      #can't find any a characters in the string
end

但是我收到了这个错误:

07-most-letters.rb:10:in `nearby_az': undefined method `-' for true:TrueClass (NoMethodError)                                                                                                 
        from 07-most-letters.rb:20:in `<main>'

plz help

2 个答案:

答案 0 :(得分:1)

((ind2=string.index(?z,ind1)!=nil),您将ind2设置为string.index(?z,ind1)!=nil,这是一个布尔值。您可以将ind2=string.index(?z,ind1)分组以避免这种情况:

return (((ind2=string.index(?z,ind1))!=nil) and ((ind2-ind1) <= 3))

答案 1 :(得分:0)

如果z必须遵循a,请考虑以下事项:

def nearby_az(str)
  (ia = str.index('a')) && (iz = str.index('z', ia)) && iz - ia <= 3
end

nearby_az("There is alwzys the..") #=> true
nearby_az("There is always zee..") #=> false
nearby_az("There'z always the..")  #=> nil

如果您希望始终返回truefalse(而不是假值nil),请将操作行更改为:

!!((ia = str.index('a')) && (iz = str.index('z', ia)) && iz - ia <= 3)

如果z可以在a之前或之后,则修改如下:

def nearby_az(str)
  (ia = str.index('a')) && (iz = str.index('z', [ia-3,0].max)) &&
    (iz - ia).abs <= 3
end

nearby_az("There is alwzys the..") #=> true
nearby_az("There is always zee..") #=> false
nearby_az("There'z always the..")  #=> true