Created
October 15, 2017 12:41
-
-
Save xiangzhuyuan/cd0976cbd1250e0546a82af3f69e1178 to your computer and use it in GitHub Desktop.
forwardable_example.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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