Skip to content

Instantly share code, notes, and snippets.

@xiangzhuyuan
Created October 15, 2017 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiangzhuyuan/cd0976cbd1250e0546a82af3f69e1178 to your computer and use it in GitHub Desktop.
Save xiangzhuyuan/cd0976cbd1250e0546a82af3f69e1178 to your computer and use it in GitHub Desktop.
forwardable_example.rb
require 'forwardable'
## MyQueue クラスの定義
class MyQueue
extend Forwardable
def initialize
@q = [] # 委譲するオブジェクトの準備
end
# 望ましいインターフェースの enq() と deq() を定義
def_delegator :@q, :push, :enq
def_delegator :@q, :shift, :deq
# キューにも合ういくつかの一般的な Array のメソッドをサポート
def_delegators :@q, :clear, :first, :push, :shift, :size
end
## 利用例
q = MyQueue.new
q.enq 1, 2, 3, 4, 5
q.push 6
q.shift # => 1
while q.size > 0
puts q.deq
end
q.enq "Ruby", "Perl", "Python"
puts q.first
q.clear
puts q.first
#このプログラムの出力結果は次のようになります。
#2
#3
#4
#5
#6
#Ruby
#nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment