在 C 编程中,我相信他们称之为通过引用传递。我想做的就是这个。
class A
attr_accessor :foo
def initialize
@foo = 'foo'
end
def get_b
_b = Object.new
_b.extend B
_b.foo = @foo
end
module B
attr_accessor :foo
def change_foo
@foo = 'bar'
end
end
end
a = A.new
puts a.foo # 'foo'
b = a.get_b
puts b.foo # 'foo'
b.change_foo
puts b.foo # 'bar'
puts a.foo # This should also be 'bar' but is instead still 'foo'
在 b.change_foo
之后,我想修改 a.foo
的值。有没有办法将 @foo
的引用从 class A
传递给 module B
而不是值?
最佳答案
通过这个具体的字符串示例,您可以让它发挥作用。
module B
attr_accessor :foo
def change_foo
# @foo = 'bar' # this won't work
foo.replace('bar')
end
end
当你执行 @foo = 'bar'
时,你将完全断开 B 的 foo
和 A 的 foo
之间的任何连接. 它们现在是两个独立的对象。
上面的代码所做的是,不是创建另一个对象,而是使用对该对象的引用来调用它的方法(这将改变它的状态)。将同样适用于其他可变对象(数组、散列、自定义类的实例)。但不是像整数这样的不可变原语。
Is there a way of passing the reference of @foo from class A to module B instead of the value?
引用(或 C 语言中的“指针”)实际上已传递到此处。然后覆盖它。
关于Ruby 修改原始变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944962/