ruby-on-rails - Ruby——使用父实例变量的子类

标签 ruby-on-rails ruby inheritance

class A
  def initialize(var)
    @var = var
  end
end

class B < A
  def initialize
  end

  def test
    puts @var
  end
end

a = A.new('hello')

b = B.new
b.test

此代码不起作用,因为 b 继承自 A 而不是 a

在 Ruby(或 Rails)中,我如何获得这种行为?继承对共享方法有用,是否也可以共享数据?


更新

这个问题有点困惑,所以我会尽力澄清。

我希望 B 的实例不仅从类 A 继承,而且还从 A 的实例继承。这样,我就可以做这样的事情:

a1 = A.new('one')
a2 = A.new('two')
b1 = a1.B.new # not ruby syntax, but this is why I'm asking the question
b2 = a2.B.new
b3 = a2.B.new

b3.test
#=> 'two'
b2.test
#=> 'two'
b1.test
#=> 'one'

最佳答案

实现目标的一种快速方法是使用鲜为人知的 SimpleDelegator类:

class A
  attr_reader :var

  def initialize(var)
    @var = var
  end
end

require 'delegate'

class B < SimpleDelegator
  def test
    puts var
  end
end

a1 = A.new('one')
a2 = A.new('two')
b1 = B.new(a1)
b1 = B.new(a1)
b2 = B.new(a2)
b3 = B.new(a2)

b3.test
#=> 'two'
b2.test
#=> 'two'
b1.test
#=> 'one'

blog article (“将您的工作转发给 Ruby 中的其他对象的 5 种方式”)您可能会感兴趣。

关于ruby-on-rails - Ruby——使用父实例变量的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060649/

相关文章:

ruby - 使用 RVM : make "-j" argument 安装 Ruby 时出错

c++ - 你如何为具有继承的 C++ 类编写 C 包装器

ruby-on-rails - 从 AASM 的模型中获取状态/事件列表

ruby-on-rails - 如何检查变量是否有错误

ruby-on-rails - 在 Rails 控制台和 Controller 中需要一个 Ruby 模块

ruby - 用于传递哈希的独特构造

ruby - 无法通过 gsub 和 ||= ruby​​ 方法解析多个电话号码

c++ - 允许类模板的模板参数在派生类中可见

ruby - 使用类似 django 的液体 block /继承的 Jekyll 模板

javascript - 用于搜索引擎可抓取应用程序的 EmberJS 技术栈