lundi 28 septembre 2015

Boolean behaving strange, logic issue

I'm having an issue with boolean expected behavior. I can make the desired result but I'm not sure why the strange behavior occurs. This:

def palindrome?(string)
  rev = string.reverse
  if rev == string
    true
  else
    false
  end
end

produces a wrong result:

palindrome?("abc") == false: true
palindrome?("abcba") == true: true
palindrome?("z") == true: true

while this:

def palindrome?(string)
  rev = string.reverse
  if rev == string
    true
  end
end

produces the correct result:

palindrome?("abc") == false: false
palindrome?("abcba") == true: true
palindrome?("z") == true: true

The following might be similar:

def nearby_az(string)
  counter = 0
  string = string.split("")
  if string.count == 1
    false
  elsif (string.index("z") - string.index("a")) <= 3
    true
  else
    false
  end
end

nearby_az("a") == false: true
nearby_az("z") == false: true

Aucun commentaire:

Enregistrer un commentaire