John - 1 year ago 81

Ruby Question

I am trying to develop a function which will return the longest palindrome substring of an entered string. I am right now working on breaking up the string so that each subsection could then be analyzed to see if it is a palindromeThe code is as follows:

`def longest_palindrome(s)`

place = 0

array = s.chars

output = []

while place < s.length

output << (array[0]..array[place]).to_a

place += 1

end

return output

end

if given string "ababa" I would expect the resulting array to look like this:

`[["a"],["a","b"],["a","b","a"],["a","b","a","b"],["a","b","a","b","a"]]`

However, when i return the output array this is what is stored inside:

`[["a"], ["a", "b"], ["a"], ["a", "b"], ["a"], ["a", "b"]]`

What about my function is causing this to happen?

Answer Source

You're misusing the range operator to produce ranges like `'a'..'a'`

, which is just `'a'`

.

The two array indexing operations have no idea of each other, or that the returned variable will be used in a range. Each returns a single character. You're getting `array[0]`

, which is `a`

, and `array[place]`

which alternates between `a`

and `b`

, and producing the ranges `'a'..'a'`

and `'a'..'b'`

over and over.

The correct range is produced using `array[0..place]`

, which returns the sub-array from `0`

to `place`

, inclusive.