Ruby中的对象分配 [英] Object assignment in Ruby
问题描述
来自c ++背景,我对Ruby中的对象分配感到好奇.对于以下对象分配,应考虑哪些因素(如果有的话):
Coming from a c++ background I'm curious about object assignment in Ruby. What considerations (if any) should be made for the following object assignments:
class MyClass
attr_accessor :a, :b
def initialize(a, b)
@a = a
@b = b
end
def some_method
puts "#{self.a} #{self.b}"
end
end
m = MyClass.new("first", "last")
n = MyClass.new("pizza", "hello")
q = n
q.some_method
推荐答案
如果您熟悉C ++,则可能希望将Ruby中的每个变量(实例或其他实例)都视为对另一个对象的引用.由于Ruby中的所有内容都是对象,即使nil
也是NilClass类型的对象,在任何情况下都适用.
If you're familiar with C++, then you might want to consider every variable in Ruby, instance or otherwise, as a reference to another object. Since everything in Ruby is an object, even nil
, which is of type NilClass, this holds true under every circumstance.
要确定要引用的对象,可以使用object_id
方法进行区分.这类似于在C ++中使用&
转换为指针.
To determine which object you're referencing, you can use the object_id
method to differentiate. That's similar to converting to a pointer using &
in C++.
考虑一下:
a = "foo"
b = a
a.object_id == b.object_id
# => true
由于a
是对该字符串的引用,而b
是a
的副本,因此它们实际上是对同一对象的不同引用.
Since a
is a reference to that string, and b
is a copy of a
, then they are actually different references to the same object.
这很重要,因为修改对象的操作会同等影响所有对该对象的引用:
This is important because operations that modify an object affect all references to that equally:
a << "bar"
# => "foobar"
b
# => "foobar"
但是,创建 new 对象的操作不会修改所有副本:
However, operations that create a new object will not modify all copies:
a += "baz"
# => "foobarbaz"
b
# => "foobar"
!
标识了Ruby中的许多方法,以区分就地版本和新副本版本,但这并非总是如此,因此您必须熟悉每种方法才能确定.
Many methods in Ruby are identified by a !
to distinguish in-place versus new-copy versions, but this is not always the case, so you have to be familiar with each method in order to be sure.
通常,一项任务会将旧的引用替换为新的引用,因此,根据经验,=
将替换旧的引用.这适用于+=
,-=
,||=
,&&=
等.
Generally an assignment will replace an old reference with a new one, so as a rule of thumb, =
will replace old references. This applies to +=
, -=
, ||=
, &&=
and so on.
根据Phrogz关于使用ObjectSpace._id2ref(object_id)
将对象标识符转换为对象的注释进行了更新.
Updated based on Phrogz's comment about using ObjectSpace._id2ref(object_id)
to convert an object identifier into an object.
这篇关于Ruby中的对象分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!