rubyのクラス同士の継承関係を比較する演算子についてのメモ。

   1  >> class Foo;end
   2  >> class Bar<Foo;end
   3  >> class Baz<Foo;end
   4  >> [Foo < Bar, Bar < Foo, Foo > Bar, Bar > Foo]
   5  => [false, true, true, false]
   6  >> Foo <=> Bar
   7  => 1
   8  >> Foo <=> String
   9  => nil
  10  >> Bar <=> Foo
  11  => -1
  12  >> Bar <=> Baz
  13  => nil

また、以下のようにモジュールのinclude関係も取得出来ます。

   1  >> module Goo;end
   2  >> class Foo;include Goo end
   3  >> Foo < Goo
   4  => true
   5  >> Foo > Goo
   6  => false
   7  >> Goo < Foo
   8  => false
   9  >> Goo > Foo
  10  => true

posted by Png genki on Sun 25 Jan 2009 at 20:47

Rubyで、クラスの内部から基底クラスのメソッドを呼び出す場合は、 superを使えば良いのですが、 どうしても外部から基底クラスのメソッドを呼び出したい場合には、 以下のようにすれば実現出来ます。

   1  >> class Foo; def foo; puts "foo#{self}"; end end
   2  => nil
   3  >> class Bar < Foo; def foo; puts "bar#{self}"; end end
   4  => nil
   5  >> Bar.new.foo
   6  bar#<Bar:0x25c2d60>

このように、通常は基底クラスのメソッドを直接呼び出す事は出来ませんが、

   1  >> Foo.instance_method(:foo).bind(Bar.new).call
   2  foo#<Bar:0x25b7f00>

一度UnboundMethodにしてから、もう一度バインドする事で、 基底クラスのメソッドを呼び出す事が出来ます。

posted by Png genki on Sun 25 Jan 2009 at 06:43
Contents
継承関係を比較する演算子
外部から基底クラスのメソッドを呼び出す方法のメモ
Comments
瀧内元気: MacOS版は以下にあります * [genki/ViMouse](https://githu... '23-1
dsjf: https://gist.github.com/6bf1bf2c3cbb5eb6e7a7 これ... '13-1
瀧内元気: おお、チェックしてみます。thx! '11-12
overisland: Reeder for iPhone もこの UI を実装していますね。 '11-12
瀧内元気: その情報は見たのですが、以下のサイトによると、現在はまた必要になってるっぽいんですよね。 ... '11-12
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ