Ruby String Arrays覆盖自己?

时间:2015-06-18 04:10:34

标签: ruby-on-rails arrays ruby string overwrite

由于某种原因,字符串被操作镜像重写为镜像[j] = string [i]

我不知道为什么会这样,我没有指挥它。我的反向(字符串)函数的输出将停在中间,如: ABCDEF - > FEDDEF 但我试图这样做: 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 个答案:

答案 0 :(得分:4)

您需要使用#dup。在您的情况下,mirror = string表示两个变量都持有同一对象的引用。因此,当您更改对象时,可以通过stringmirror反映出来。

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"