A implementation of delegate pattern (2)

Secondly,write a delegator in another way
1.Code a class extends DelegateClass,and set a parameter that you want to use
2.Implementing your method initialize ,and donot forget to write super method.
3.Implementing your method which match to a parameter before you passed
4.And now,let's code
require 'delegate'

class MyDelegator < DelegateClass(Array)
  def initialize(array)
    super(array)
  end
  def [](*n)
    val = super(*n)
    #Add your logic here
  end
end


and now ,when u add your logic at method [](*n),the class MyDelegator willdelegate method [] of a Array ,just like this

array = %w{22 33 33 44}
myDelegator = MyDelegator.new(array)
puts array[0..3]

It will be output the result that u changed in your logic.

你可能感兴趣的:(Ruby)