Skip to content

Instantly share code, notes, and snippets.

@kmdsbng
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save kmdsbng/8be1b51141463e44f41f to your computer and use it in GitHub Desktop.

Select an option

Save kmdsbng/8be1b51141463e44f41f to your computer and use it in GitHub Desktop.
### 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が導入された。
### sample5
public
def toge
'suge'
end
Object.public_instance_methods.grep /toge/ # => [:toge]
toge # => "suge"
self.toge # => "suge"
# トップレベルでpublicメソッドを呼び出すと、以降に定義されたメソッドは、
# Objectクラスのパブリックインスタンスメソッドになる。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment