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
class Murajun | |
def initialize(name) | |
@name = name | |
end | |
def murajun? | |
@name == "murajun" | |
end | |
end | |
class Name | |
def hello_murajun(name) | |
if name.murajun? | |
"Hello, murajun." | |
else | |
"You're not murajun." | |
end | |
end | |
end | |
murajun = Murajun.new("murajun1978") | |
name = Name.new | |
p name.hello_murajun(murajun) # => You're not murajun. |
murajunクラスでmurajun?メソッドを定義しているよねー
そのオブジェクトをnameクラス(名前アカンやつ)のhello_murajunメソッドに引数で渡してる。
murajun?メソッドだけなら、Stringクラスにモンキーパッチできるよねー
でも、このときだけmurajunかどうか判定したい場合は???
そんな時の特異メソッドですよ
murajun_name = "murajun" def murajun_name.murajun? self == "murajun" end name = Name.new p name.hello_murajun(murajun_name) # => Hello, murajun.
特定の条件下だけ、ある機能を実装したい場合に便利ですね。
( ̄(エ) ̄)彡☆
0 件のコメント:
コメントを投稿