Ruby String Arrays Overwriting Themselves?

96 views Asked by At

For some reason, string is getting rewritten as mirror by the operation mirror[j] = string[i]

I have no idea why this would be, I'm not commanding it to. The outputs of my reverse(string) function will stop at the middle, like: ABCDEF -> FEDDEF but I'm trying to do: ABCDEF -> FEDCBA

def reverse(string)
  mirror = string
  i = string.length - 1
  j = 0
  while j < string.length
    mirror[j] = string[i]
    puts(mirror)
    j = j + 1
    i = i - 1
  end
  return mirror
end
1

There are 1 answers

2
Arup Rakshit On BEST ANSWER

You need to use #dup. In your case, mirror = string means both the variables are holding the reference of the same object. So, when you change the object, that can be reflected through both string and mirror.

def reverse(string)
  mirror = string.dup
  i = string.length - 1
  j = 0
  while j < string.length
    mirror[j] = string[i]
    j += 1  # same as j = j + 1
    i -= 1  # same as i = i - 1
  end
  mirror 
  # last expression is returned by default, so you can write only  `mirror` instead of `return mirror`
end

p reverse 'ABCDEF' # "FEDCBA"