Ruby变量(数组)赋值误区(用push方法) [英] Ruby variable (Array) assignment misunderstanding (with push method)
问题描述
我发现我对 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
输出是
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
问题 A:push
到 local_ar_2
如何改变另外两个数组?我对局部变量的理解是,一旦它们被创建,它们就不应该影响任何其他变量,因为它们是局部的.
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.
问题 B:我怎样才能避免这样的事情发生?来自 C 和 Perl,这让我大吃一惊.
Question B: How can I avoid things like this from happening? Coming from C and Perl this is just blowing my mind.
推荐答案
Ruby 使用引用!记在脑子里.如果你想要一个副本,你必须这样做:
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
示例:
a = ["a", "b", "c"]
b = a[0]
b = "d" # We assign a new object to b!
a
是:=> ["a", "b", "c"]
a
is:
=> ["a", "b", "c"]
但是:
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
是:=>你好"
但是:
a = "hello"
b = a
b<<" world"
# We are working with the reference!
a
是:=>你好世界"
a = "abc"
b = a
b[0] = "d" # we are working with the reference
a
是:=> "dbc"
a
is:
=> "dbc"
您可以在此处阅读有关它的所有内容:http://ruby-doc.org/docs/ProgrammingRuby/.向下滚动到几乎位于页面底部的变量".
You can read everything about it here: http://ruby-doc.org/docs/ProgrammingRuby/. Scroll down to "Variables" almost at the bottom of the page.
这篇关于Ruby变量(数组)赋值误区(用push方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!