gpt4 book ai didi

ruby - 变量变化值,ruby

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:36 26 4
gpt4 key购买 nike

我不确定这个名为 origString 的变量如何在我的循环中改变值

def scramble_string(string, positions)
i = 0
origString = string
puts origString
newString = string
while i < string.length
newString[i] = origString[positions[i]]
i = i + 1
end
puts origString
return newString
end

例如,如果我运行 scramble_string("abcd", [3, 1, 2, 0])origString 从第一个“puts”中的“abcd”变为第二个中的“dbcd”。如果我只声明一次,如何更改 origString 的值?

最佳答案

当您在 Ruby 中说 x = y 时,会创建一个引用完全相同对象的变量。对 x 的任何修改都将应用于 y,反之亦然:

y = "test"
x = y

x[0] = "b"

x
# => "best"
y
# => "best"

你可以这样判断:

x.object_id == y.object_id
# => true

它们是相同的对象。你想要的是先复制一份:

x = y.dup
x[0] = "b"
x
# => "best"
y
# => "test"

这导致两个独立的对象:

x.object_id == y.object_id
# => false

所以在您的情况下,您需要将其更改为:

orig_string = string.dup

话虽如此,在 Ruby 中处理事物的最佳方式通常是使用返回副本的函数,而不是就地操作事物。更好的解决方案是:

def scramble_string(string, positions)
(0...string.length).map do |p|
string[positions[p]]
end.join
end

scramble_string("abcd", [3, 1, 2, 0])
"dbca"

请注意,这比使用字符串操作的版本简洁得多。

关于ruby - 变量变化值,ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46028795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com