16
名名名名名 名名名 名名名名 名名名名 ・・ 名名名名名Nguyễn Văn Đức 名名名名名名 : 名名 名名23 名 名名 名名名名名名名 名名 名名名名名 :、 PC 名名名

Ruby under the hood

Embed Size (px)

Citation preview

Page 1: Ruby   under the hood

名前: 日本語: グエン・ヴァン・ドゥック ベトナム語: Nguyễn Văn Đức

ニックネーム : レン年齢: 23際大学:ハノイ工科大学趣味:スポーツ、 PCゲーム

Page 2: Ruby   under the hood

Ruby - under the hood

Page 3: Ruby   under the hood

Problem

Page 4: Ruby   under the hood
Page 5: Ruby   under the hood
Page 6: Ruby   under the hood

Ruby - under the hood

1.Method lookup - ancestor

2.How to change method lookup path

3.Summary

Page 7: Ruby   under the hood

Method lookup

Rubyはメソッドを実行するとき、クラス自身、親クラス、親の親クラス、 ...という順番でメソッドを探しに行きますよね?何となくイメージはできるけど、実際にその動作をどうやって確認しますか?それに、親や子供などの関係がなく、 includeなどを使う場合に、メソッドを実行する順番はどのようになるでしょうか?

Page 8: Ruby   under the hood

Ancestors

Rubyには、 ancestorsというメソッドがあります。このメソッドは、関連する全てのクラスを配列にして返します。ancestorsで得られたクラスの配列の中にメソッドが存在するか、順番に探して、見つけたらそのメソッドを実行します。

Page 9: Ruby   under the hood

Ancestor

この順番によると、最初は Basicクラスでメソッドを探す次は Blunch,JFC、。。

Page 10: Ruby   under the hood

Ancestors

デフォルトだと ancestorsで得られる配列の中で、一番最初に見つけたクラスのメソッドが実行されます。でも、他のモジュールのメソッドを実行したい場合、どうすれば良いのでしょうか? (ancestorsチェーンの順番を変えたい )

クラスで他のモジュールを includeしたり、 prependしたり、他のクラスをextendしたりすると、 ancestorsチェーンが変更されます。

Page 11: Ruby   under the hood

Include

クラスで他のモジュールを Includeすると、セルフクラスの次に入ります

Page 12: Ruby   under the hood

Prepend

クラスで他のモジュールを prependすると、逆に ,セルフクラスの前に入ります

Page 13: Ruby   under the hood

Another

1.super

ancestorsチェーンの中で次に見つかった同じメソッド名を実行します。

Page 14: Ruby   under the hood

Another

2. alias

Page 15: Ruby   under the hood

Summary

これは、マジックでは、ありません。

Page 16: Ruby   under the hood

ご清聴ありがとうございます。