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.