由于某种原因,字符串被操作镜像重写为镜像[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
答案 0 :(得分:4)
您需要使用#dup
。在您的情况下,mirror = string
表示两个变量都持有同一对象的引用。因此,当您更改对象时,可以通过string
和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"