Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby variable (Array) assignment misunderstanding (with push method)

Tags:

ruby

I have discovered a flaw in my understanding of Ruby or programming theory or both. Look at this Code:

#!/usr/bin/ruby -w
@instance_ar = [1,2,3,4]
local_ar = @instance_ar
local_ar_2 = local_ar
###
irrelevant_local_ar = [5,6,7,8]
###
for i in irrelevant_local_ar
    local_ar_2.push(i)
end
count = 0
for i in local_ar_2
    puts "local_ar_2 value: #{i} and local_ar value: #{local_ar[count]} and @instance_ar value: #{@instance_ar[count]}\n"
    count += 1
end

The output of that is

local_ar_2 value: 1 and local_ar value: 1 and @instance_ar value: 1
local_ar_2 value: 2 and local_ar value: 2 and @instance_ar value: 2
local_ar_2 value: 3 and local_ar value: 3 and @instance_ar value: 3
local_ar_2 value: 4 and local_ar value: 4 and @instance_ar value: 4
local_ar_2 value: 5 and local_ar value: 5 and @instance_ar value: 5
local_ar_2 value: 6 and local_ar value: 6 and @instance_ar value: 6
local_ar_2 value: 7 and local_ar value: 7 and @instance_ar value: 7
local_ar_2 value: 8 and local_ar value: 8 and @instance_ar value: 8

Question A: How does push to local_ar_2 change the two other arrays? My understanding of local variables was that once they were created, they should not affect any other variables, being that they were local.

Question B: How can I avoid things like this from happening? Coming from C and Perl this is just blowing my mind.

like image 695
fflyer05 Avatar asked Sep 02 '26 11:09

fflyer05


1 Answers

Ruby works with references! Keep that in mind. If you want a copy you'd have to do it like:

@instance_ar = [1,2,3,4]
local_ar = @instance_ar.clone
local_ar_2 = local_ar.clone

Edit:

Examples:

a = ["a", "b", "c"]
b = a[0]
b = "d" # We assign a new object to b!

a is: => ["a", "b", "c"]

but:

a = ["a", "b", "c"]
b = a[0]
b[0] = "d" # We are working with the reference!

a is:
=> ["d", "b", "c"]

a = "hello"
b = a
b += " world" 
# Is the same as b = b + " world", we assign a new object!

a is: => "hello"

but:

a = "hello"
b = a
b<<" world"
# We are working with the reference!

a is: => "hello world"

a = "abc"
b = a
b[0] = "d" # we are working with the reference

a is: => "dbc"

You can read everything about it here: http://ruby-doc.org/docs/ProgrammingRuby/. Scroll down to "Variables" almost at the bottom of the page.

like image 154
sled Avatar answered Sep 04 '26 04:09

sled