-
-
Save nabetani/6203650 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
#!/usr/bin/ruby | |
# -*- coding: utf-8 -*- | |
# GistID: 6203578 | |
=begin | |
Rubyのリファレンスマニュアル( http://doc.ruby-lang.org/ja/2.0.0/doc/spec=2fdef.html#alias ) | |
「別名を付けられたメソッドは、その時点でのメソッド定義を引き継ぎ、元のメソッドが再定義されても、 | |
再定義前の古いメソッドと同じ働きをします。あるメソッドの動作を変え、 | |
再定義するメソッドで元のメソッドの結果を利用したいときなどに利用されます。」 | |
の通り、 | |
eql?を再定義してから | |
alias == eql? しないと | |
==が意図通りtrueにならない例と、なる例。 | |
=end | |
class AliasBeforeOverriding | |
attr_reader :a | |
alias == eql? | |
def initialize a | |
@a = a | |
end | |
def eql? other | |
print "#{self.class}##{__method__} => " | |
@a == other.a | |
end | |
end | |
class OverrideBeforeAlias | |
attr_reader :a | |
def initialize a | |
@a = a | |
end | |
def eql? other | |
print "#{self.class}##{__method__} => " | |
@a == other.a | |
end | |
alias == eql? | |
end | |
a1 = AliasBeforeOverriding.new 1 | |
a2 = AliasBeforeOverriding.new 1 | |
puts( a1 == a2 ) # => false | |
o1 = OverrideBeforeAlias.new 1 | |
o2 = OverrideBeforeAlias.new 1 | |
puts( o1 == o2 ) # => true | |
puts( a1 == o1 ) # => false | |
puts( o1 == a1 ) # => true | |
puts "same class definition again." | |
class AliasBeforeOverriding | |
attr_reader :a | |
alias == eql? | |
def initialize a | |
@a = a | |
end | |
def eql? other | |
print "#{self.class}##{__method__} => " | |
@a == other.a | |
end | |
end | |
class OverrideBeforeAlias | |
attr_reader :a | |
def initialize a | |
@a = a | |
end | |
def eql? other | |
print "#{self.class}##{__method__} => " | |
@a == other.a | |
end | |
alias == eql? | |
end | |
puts( a1 == a2 ) # => true ** last time, a1 == a2 was false ** | |
puts( o1 == o2 ) # => true | |
puts( a1 == o1 ) # => true ** last time, a1 == o1 was false ** | |
puts( o1 == a1 ) # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment