Ruby 修改原始变量

标签 ruby class reference

在 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/

相关文章:

ruby - Chef - 在后台运行长时间运行的脚本

ruby - 为什么不匹配交替中更长的标记?

javascript - 仅将 Ember.js 用于 Rails 应用程序的一部分的最直接方法是什么?

javascript - 如何将 JSON 对象重新持久化为具有关联方法的对象?

c# - 我需要一些 C# 泛型说明

c++ - 你能在 ctor 中设置 weak_ptr<> 吗?

css - Ruby on Rails 样式表渲染文件和带有通用 css 的 application.css

ruby - 是否有类似于 Class#inherited 的钩子(Hook),仅在 Ruby 类定义后触发?

c# - 通过值与引用构造数据读取器时处理数据读取器

java - 查找对象引用