简体   繁体   中英

Variable changing value, ruby

I am not sure how this variable called origString is changing value in my loop

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

for example if I run scramble_string("abcd", [3, 1, 2, 0]) origString changes from "abcd" in the first "puts" to "dbcd" in the second one. How am I changing the value of origString if I am only declaring it once?

When you say x = y in Ruby that creates a variable with a reference to exactly the same object. Any modifications to x will apply to y and vice-versa:

y = "test"
x = y

x[0] = "b"

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

You can tell because of this:

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

They're identical objects. What you want is to make a copy first:

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

This results in two independent objects:

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

So in your case what you need is to change it like:

orig_string = string.dup

Now that being said, often the best way to process things in Ruby is by using functions that return copies, not manipulating things in place. A better solution is this:

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"

Note that's a lot more succinct than the version with string manipulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM