Created
October 16, 2017 12:56
-
-
Save xiangzhuyuan/669be296577815d907a6147c7edcf970 to your computer and use it in GitHub Desktop.
#SingleForwardable の使用例 # #ここでは、SingleForwardable の使用例として、委譲を使って出力機能を実現する例を紹介します。この例も RDoc から持って来ました*3。 # #例では、String クラスのインスタンスに対して、puts メソッドを STDOUT オブジェクトに委譲しています。
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' | |
printer = String.new | |
printer.extend SingleForwardable # 委譲するオブジェクトの準備 | |
printer.def_delegator "STDOUT", "puts" # STDOUT.puts() への委譲を定義 | |
printer.puts "Howdy!" | |
#実行すると標準出力に「Howdy!」と出力されます。 | |
#この例では String のインスタンスを委譲元に使っていますが、委譲元のオブジェクトのクラスには深い意味はなく、委譲するメソッドが定義されていないオブジェクトなら何でも良いと思います。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment