Ruby 函数中的字符串数组赋值

String array assignment in Ruby function

我是 Ruby 的新手,总体上对编程还很陌生。不知道为什么 string[n]=temp[string.length-(n+1)] 会将 temp 更改为字符串数组。赋值不是只更改字符串数组吗?我已经在这个问题上解决了 4 个小时,非常感谢任何帮助 =) 谢谢!

 def reverse(string)
  temp = string
  n=0
  while (string.length - n) > 0 
    string[n]=temp[string.length-(n+1)]
    n+=1
  end
  return string
end

puts reverse("abc")

tempstring 是同一个对象,因为:

temp = string

因此,对 string 的任何更改都将反映在 temp 中。您可以复制字符串变量来避免此问题:

temp = string.dup