Last active
May 2, 2018 00:17
-
-
Save hachi8833/8229e2c43aee40e651914e9da4fe21af to your computer and use it in GitHub Desktop.
The Ruby code what I see beauty in
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
# Sandi Metz「オブジェクト指向設計実践ガイド」でリファクタリング後のduck-typingコードを美しいと思い | |
# それに触発されて書いたHello worldです。 | |
# なおこのコードはRubyとGobyどちらでも動きます。 | |
# Greetクラス | |
class Greet | |
attr_accessor :audience, :head, :tail | |
def initialize | |
@head = 'Hello, ' | |
@tail = '!' | |
end | |
def name | |
audience.name | |
end | |
def say | |
puts head + name + tail | |
end | |
end | |
# MyNameモジュールでクラス名取得を共通化 | |
module MyName | |
attr_reader :name | |
def initialize | |
@name = self.class.to_s | |
end | |
end | |
#---------- | |
# 利用例: Worldクラス | |
class World | |
include MyName | |
end | |
greet = Greet.new | |
greet.audience = World.new | |
greet.say | |
# 利用例: Rubyクラス | |
class Ruby | |
include MyName | |
end | |
greet.audience = Ruby.new | |
greet.say | |
# 利用例: Gobyクラス | |
class Goby | |
include MyName | |
end | |
greet.audience = Goby.new | |
greet.say |
Author
hachi8833
commented
May 1, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment