Home > OS >  Ruby: How do I prevent a array from being modified when passed to a method?
Ruby: How do I prevent a array from being modified when passed to a method?

Time:11-16

I'm trying to pass an array into a method. The idea is a random number is generated, i, and the value of xArray[i] is copied into yArray[x], where x = 0 is increased with each run.

What I don't understand is the array I pass into the method is modified as well. For example:

# inputArray is populated by the capital letters of the alphabet, e.g. "A", "B", ... "Z"
def populateArray inputArray
    xArray = inputArray
    yArray = Array.new

    i = 0
    while yArray.length < 26
        # Subtract i to take into account decreasing array size
        x = rand(26-i)
        yArray[i] = xArray[x]

        # Delete entry so I don't get duplicate letters
        xArray.delete_at(x)
        i = i   1
    end
end

puts "inputArray length: #{inputArray.length.to_s}"
puts "xArray length: #{xArray.length.to_s}"
puts "yArray length: #{yArray.length.to_s}"

I can understand why xArray.length is 0, because that is the one I have been removed entries from. But why is it also affecting inputArray?

I have tried creating a copy by doing this: xArray = inputArray, but it doesn't seem to make a difference.

I'm expecting the inputArray to maintain its length, and have the values inside untouched.

NOTE: I am entirely new to Ruby, and have only covered the "Learn to Program" section recommended on the Ruby website. Any suggestions about formatting and easier ways to do things are always welcome.

CodePudding user response:

In your code you are using xArray = inputArray, which does not create a new array. It defines a new variable that points at the same array as inputArray. So there are not two arrays, there is just one array referenced by two variables.

For that reason, xArray.delete_at(x) is not removing an element from the copy, but from the original array instead.

If you really want to make a copy of the array, you need to use .dup (see method documentation in https://apidock.com/ruby/Object/dup). xArray = inputArray.dup would work the way you are describing, and inputArray would not be updated whenever elements are removed from xArray.

CodePudding user response:

There is concept of shallow copy and deep copy. You are doing shallow copy here. In shallow copy, only reference address copies of original copy. While in deep copy, original copy and the repetitive copies both store.

You should try this:

xArray = inputArray.dup
  • Related