Friday, September 05, 2008

RubyのTopLevelは両生類だ!

  • そこで定義されたメソッドはObjectのprivateメソッドになる。だからObjectクラス
  • publicにすることもできる
  • Singletonメソッドを定義できる。だからmainインスタンス

   1  #!/usr/local/bin/ruby

   2  # encoding: utf-8

   3  module Kernel

   4    def ker_pub_hello

   5      "hello of Kernel Public called from #{self}"

   6    end

   7    private

   8    def ker_pri_hello

   9      "hello of Kernel Private called from #{self}"

  10    end

  11  end

  12  

  13  class Object

  14    def obj_hello

  15      "hello of Object called from #{self}"

  16    end

  17  end

  18  

  19  def top_hello

  20    "hello of Top called from #{self}"

  21  end

  22  class << self

  23    def top_singleton_class_hello

  24      "hello of Top Singleton Class from #{self}"

  25    end

  26  end

  27  def self.top_singleton_hello

  28    "hello of Top Singleton from #{self}"

  29  end

  30  public

  31  def sel

  32    self.select{ |m| m =~ /hello$/  }

  33  end

  34  

  35  

  36  main = Object.new

  37  main.obj_hello # => "hello of Object called from #<Object:0x11a30>"

  38  

  39  ker_pub_hello       # => "hello of Kernel Public called from main"

  40  ker_pri_hello       # => "hello of Kernel Private called from main"

  41  self.ker_pub_hello  # => "hello of Kernel Public called from main"

  42  obj_hello           # => "hello of Object called from main"

  43  top_hello           # => "hello of Top called from main"

  44  self.top_singleton_class_hello # => "hello of Top Singleton Class from main"

  45  self.top_singleton_hello # => "hello of Top Singleton from main"

  46  

  47  self # => main

  48  self.class # => Object

  49  self.methods(true).sel # => ["top_singleton_class_hello", "ker_pub_hello", "top_singleton_hello", "obj_hello"]

  50  self.private_methods(false).sel # => ["top_hello"]

  51  self.singleton_methods(false) # => ["public", "to_s", "include", "top_singleton_hello", "private", "top_singleton_class_hello"]

  52  

  53  Object.private_instance_methods(false).sel # => ["top_hello"]

  54  Object.included_modules # => [Kernel]

  55  Kernel.private_instance_methods.sel # => ["ker_pri_hello"]

  56  Kernel.instance_methods.sel # => ["ker_pub_hello"]

  57  

  58  class H

  59    top_hello # => "hello of Top called from H"

  60    def k

  61      top_hello

  62    end

  63  end

  64  H.new.k # => "hello of Top called from #<H:0xe6a0>"

No comments: