变化值,红宝石

时间:2017-09-03 23:55:04

标签: ruby

我不确定这个名为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的值?

1 个答案:

答案 0 :(得分:4)

当你在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"

请注意,与使用字符串操作的版本相比,它更简洁。