3

I'm going through some exercises on App Academy Open, and I've come across a test case that I can't quite figure out. I've written a method to detect if a given string is a palindrome or not, and it seems to work fine for all strings I've thrown at it - apart from 'xabcx'. Am I missing something?

def palindrome?(str)
  (str.length / 2).times do |idx|
    if str[idx - 1] != str[idx * -1]
      return false
    end
  end
  true
end

p palindrome?("xabcx")

I expect an output of false, but I get true. The method works as expected for every other word I've tried.

nashsibanda
  • 31
  • 1
  • 4

1 Answers1

2

As Cary Swoveland already pointed out your indexing is wrong. To make debugging easier for you the next time I would recommend printing out both the values of the indices your using as well as the actual value of the char you select from the strings for each iteration of the loop.

As an alternative and really shorter and simpler version you could also use:

def palindrome?(str)
  str == str.reverse
end

or - taking into account ignoring upper / lower case:

def palindrome?(str)
  str.downcase == str.downcase.reverse
end
BBB
  • 302
  • 2
  • 10
  • "and really shorter and simpler version" - and significantly more wasteful. Requires O(N) memory. JFYI. – Sergio Tulentsev Jul 15 '19 at 16:45
  • Thanks for the comment and suggestion. The exercise in question specifically prohibits using the reverse function, but adding downcase to the method is a great idea! – nashsibanda Jul 16 '19 at 03:58