Ruby/Collections/Forwardable
Материал из Wiki.crossplatform.ru
(Различия между версиями)
Версия 17:10, 26 мая 2010
Easing the Delegation Blues
require "forwardable" class WriterDecorator extend Forwardable def_delegators :@real_writer, :write_line, :rewind, :pos, :close def initialize(real_writer) @real_writer = real_writer end end
extend Forwardable
require "forwardable" class AppendOnlyArray extend Forwardable def initialize @array = [] end def_delegator :@array, :<< end a = AppendOnlyArray.new a << 4 a << 5
extending Forwardable delegates to hash
require "forwardable" class RandomAccessHash extend Forwardable def initialize @delegate_to = {} end def_delegators :@delegate_to, :[], "[]=" end ra = RandomAccessHash.new ra["A"] = 4.60 ra["B"] = 1.94 ra["C"] = 2.01 puts ra["D"]