light log

学んだこととか

Rubyのトップレベルについて調べた

参考にした記事

環境

$ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]

結果

トップレベルでのselfはmainオブジェクト。

p self
#=> main

mainオブジェクトはObjectクラスのインスタンス

p self.class
#=> Object

トップレベルに定義したメソッドはmainオブジェクトのプライベートメソッドになる。

def toplevel_method
end

p self.private_methods(false).sort
#=> [:define_method, :include, :private, :public, :toplevel_method, :using]

すなわち、Objectクラスのプライベートインスタンスメソッドでもある。

def toplevel_method
end

p Object.private_instance_methods(false).sort
#=> [:toplevel_method]

すなわち、ObjectクラスもObjectクラス(を継承したClassクラス)のインスタンスなので、Objectクラスのプライベートメソッドでもある。

def toplevel_method
end

p Object.private_methods.sort
#=> [(中略), :toplevel_method, (中略)]

継承したメソッドなのでこうすると消える。

def toplevel_method
end

p Object.private_methods(false).sort
#=> [:inherited, :initialize]

Objectクラスのプライベートメソッドでありプライベートインスタンスメソッドなので、どこでも使える。

(というか、Rubyだとprivateなメソッドが継承先のクラスから見えるの初めて知った。参考:JavaやC#の常識が通用しないRubyのprivateメソッド - give IT a try

def toplevel_method
  puts 'inside of toplevel_method'
end

def foo
  toplevel_method
end

class Bar
  toplevel_method
  def baz
    toplevel_method
  end
end

foo
Bar.new.baz

#=> inside of toplevel_method
#=> inside of toplevel_method
#=> inside of toplevel_method


p Bar.private_methods.include? :toplevel_method
p Bar.private_instance_methods.include? :toplevel_method
#=> true
#=> true

まとめ

ちょっとすっきりした。

object main - Ruby 2.2.0 リファレンスマニュアル