Skip to content

Instantly share code, notes, and snippets.

@igrep
Created August 11, 2013 05:52
Show Gist options
  • Save igrep/6203578 to your computer and use it in GitHub Desktop.
Save igrep/6203578 to your computer and use it in GitHub Desktop.
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment