0

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.

1
  • what is the length and content of inputArray that you get? right now I see a method definition and some "puts" but not how you actually call the method and how your input array looks like Commented Nov 15, 2022 at 17:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.