我是Ruby新手,對於編程來說很新。不知道爲什麼string [n] = temp [string.length-(n + 1)]會將temp更改爲字符串數組。是不是隻改變字符串數組?我一直在這個問題上4個小時,任何幫助將非常感激=)謝謝!Ruby函數中的字符串數組賦值
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")
Temp和string是相同的對象。 – 2015-03-18 21:27:42
@FrederickCheung,是一個參考而不是副本? – 2015-03-18 21:30:57
如果我在'temp = string'之後加'puts'string.object_id ==#{string.object_id},temp.object_id ==#{temp.object_id}'',當我執行'reverse(「abc」)' ,將打印以下內容:'string.object_id == 70267640537340,temp.object_id == 70267640537340'。這是否告訴你什麼?你需要'temp = string.dup'(儘管我沒有看過你的其他代碼)。 – 2015-03-18 21:32:37