John John - 11 months ago 73
Ruby Question

Strange output in Ruby Longest Palindrome substring function

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
return output

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


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?


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[], which returns the sub-array from 0 to place, inclusive.