Created
February 26, 2009 08:08
-
-
Save ukstudio/70734 to your computer and use it in GitHub Desktop.
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
# DuckTypingの単純な例 | |
# ここで重要なのはSTDOUT(IOクラス)と | |
# StringIOクラスには継承関係がないとうこと。 | |
# | |
require 'stringio' | |
def message_write(out, message) | |
out.write(message) | |
end | |
message_write($stdout, "STDOUT") #$stdoutはデフォルトでSTDOUT | |
io = StringIO.new | |
message_write(io, "StringIO") | |
puts io.string | |
# つまりここではwriteメソッドがあれば | |
# クラスに囚われず柔軟に処理が書けるということ。 | |
# もちろん、writeクラスが定義されていれば | |
# オリジナルクラスでも問題ない | |
class MyClass | |
def write(str) | |
p str | |
end | |
end | |
my_class = MyClass.new | |
message_write(my_class, "my_class") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment