ruby - 自定义<<方法

标签 ruby

class Foo
  def initialize
    @bar = []
  end

  def changed_callback
    puts "Bar has been changed!"
  end

  def bar
    @bar
  end

  def bar=(a)
    @bar = a
    self.changed_callback() # (hence why this doesn't just use attr_accessor)
  end

  def bar<<(a)
    @bar.push(a)
    self.changed_callback()
  end
end

f = Foo.new()
f.bar = [1,2,3]
  => "Bar has been changed!"
f.bar << 4
  => "Bar has been changed!"
puts f.bar.inspect
  => [1,2,3,4]

这样的事情可能吗?

谢谢!

最佳答案

您需要以某种方式扩展 Foo#bar 返回的对象具有适当的#<<方法。也许是这样的?

class Foo
  module ArrayProxy
    def <<(other)
      @__foo__.changed_callback
      super
    end
  end

  def initialize
    @bar = []
  end

  def changed_callback
    puts 'Bar has been changed!'
  end

  def bar
    return @bar if @bar.is_a?(ArrayProxy)
    @bar.tap {|bar| bar.extend(ArrayProxy).instance_variable_set(:@__foo__, self) }
  end

  def bar=(a)
    @bar = a
    changed_callback # (hence why this doesn't just use attr_accessor)
  end

end

f = Foo.new
f.bar = [1,2,3]
#  "Bar has been changed!"
f.bar << 4
#  "Bar has been changed!"
puts f.bar.inspect
#  => [1,2,3,4]

关于ruby - 自定义<<方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3384285/

相关文章:

ruby - 在 Selenium 2.9 中选择图像

ruby - 如何在 Ruby 中创建无类 DSL?

ruby - 后视正则表达式 (Ruby) 的问题

ruby - File.readlines UTF-8 中的无效字节序列(ArgumentError)

ruby - 如何制作 protected 单例方法

ruby-on-rails - 为什么我不能安装 SQLite gem?

ruby-on-rails - Thinking-Sphinx-Raspell 配置

json - 通过Logstash将哈希数组转换为简单哈希

ruby - Monkeypatching Vagrant 插件

ruby - 很好地格式化输出到控制台,指定选项卡的数量