small medium large xlarge

Generic-user-small
25 May 2016, 05:16
Felipe Maion (3 posts)

Hello, writing the “shuffle” exercice I faced the following:


list = ('a'..'z').to_a
def shuffle (some_array)
unshuffled =  some_array
shuf = []
	while  unshuffled.length > 0
		rando = rand(unshuffled.length)
		sorted = unshuffled[rando]		
		shuf.push sorted
		unshuffled.delete_at(rando)
	end

return	shuf

end

puts list.length
shuf = shuffle (list)
puts list.length

>> 26
>> 0

Even with “unshuffled = some_array” the .delete_at is changing the original parameter (some_array)… at the end, my original “list” is clean.

Why??

Thank you

Generic-user-small
25 May 2016, 05:47
Felipe Maion (3 posts)

OK, I found the solution, but I still not getting why…

# change the line: "unshuffled =  some_array" to
unshuffled =  some_array.dup  # Should I use dup or clone??

WHY it is changing the original array (variable)?!?

I’ve read Chapter 4 again trying to find an answer, no deal.

Chris_beach_pragsmall
25 May 2016, 21:53
Chris Pine (72 posts)

In the original example, unshuffled = some_array does not create a new array. It’s just giving a second name to the array: you can call it some_array, or you can call it unshuffled. So when you delete something from unshuffled, you also delete it from some_array, because they are the same array.

Consider this code:


a = [1, 2, 3]
b = a

b.push 4

a now has 4 elements, because a and b are just different names for the exact same array.

In the latter example you gave, when you use some_array.dup, that actually creates a new array. So at that point, you have two different arrays, each with a different name. In that case, changing one does not change the other.

Does that make sense?

Generic-user-small
08 Jun 2016, 14:28
Felipe Maion (3 posts)

Hello, thank you for the reply!

Yeap, it makes sense.

It is not clear to me why when I do the following:

a = 4
b = a
b = 2

I create a new variable, that copies “a”, and when I change “b” it does not affect “a”, while with Array, it is not a copy, it is the same (as you mentioned).

Not sure why this happen, but it is clear to me how to fix it.

Thank you!

Chris_beach_pragsmall
08 Jun 2016, 17:28
Chris Pine (72 posts)

Variables point to objects.

When you write the following:

a = 4
b = a

a and b are both pointing to the same object. This is the case if the object is a number, or an array, or anything.

When we then write b = 2, we are saying that we want b to point to a new object (the number 2). Now a and b are pointing to different objects.

In the previous example with the array, however:

a = [1, 2, 3]
b = a

b.push 4

On that last line, we did not point b at a new object! We modified the object that b points to, but b is still pointing to same array (which is the one that a also points to). We know this because we didn’t have an assignment, like b = something_else. It’s only assignment that changes what a variable points to.

Hope that helps!

You must be logged in to comment