Created
September 19, 2014 03:04
-
-
Save kmdsbng/7fda1000f96d76ef9a04 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| ### sample1 | |
| Kernel.private_instance_methods.grep /hoge/ # => [] | |
| Object.private_instance_methods.grep /hoge/ # => [] | |
| self.private_methods.grep /hoge/ # => [] | |
| self # => main | |
| self.class # => Object | |
| def hoge | |
| 'moge' | |
| end | |
| Kernel.private_instance_methods.grep /hoge/ # => [] | |
| Object.private_instance_methods.grep /hoge/ # => [:hoge] | |
| self.private_methods.grep /hoge/ # => [:hoge] | |
| hoge # => "moge" | |
| begin | |
| self.hoge | |
| rescue Exception => x | |
| x.message # => "private method `hoge' called for main:Object" | |
| end | |
| # トップレベルでメソッド定義すると、Objectクラスの | |
| # プライベートインスタンスメソッドとして定義される。 | |
| # トップレベルのself(=main)はObjectクラスのインスタンスなので、 | |
| # hogeメソッドを呼び出すことができる。 | |
| # ただしプライベートメソッドなので、selfレシーバを明示して | |
| # 呼び出すことはできない。 | |
| ### sample2 | |
| module Kernel | |
| private | |
| def koge | |
| 'soge' | |
| end | |
| end | |
| Object.included_modules # => [Kernel] | |
| Kernel.private_instance_methods.grep /koge/ # => [:koge] | |
| Object.private_instance_methods.grep /koge/ # => [:koge] | |
| self.private_methods.grep /koge/ # => [:koge] | |
| koge # => "soge" | |
| # ObjectクラスはKernelモジュールをincludeしている。 | |
| # なので、Kernelモジュールにメソッド定義すると、トップレベル | |
| # から呼び出すことができる。 | |
| ### sample3 | |
| koge2 = Object.instance_method(:koge) | |
| koge2 # => #<UnboundMethod: Object(Kernel)#koge> | |
| koge2.bind(Object.new).call # => "soge" | |
| # 取り出したメソッドは、callで呼び出すことができる | |
| ### sample4 | |
| Object.superclass # => BasicObject | |
| BasicObject.included_modules # => [] | |
| # ObjectクラスのスーパークラスはBasicObject。 | |
| # Ruby1.9からBasicObjectが導入された。 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment