Ruby元編程小結(一) 代碼中包含變量,類和方法,統稱爲語言構建(language construct)。 # test.rb class Greeting def initialize(text) @text = text end def welcome @text end end my_obj = Greeting.new("hello") puts my_obj.class puts my_obj.class.instance_methods(false) #false means not inherited puts my_obj.instance_variables result => Greeting welcome @text 總結: 實例方法繼承於類,實例變量存在於對象自己。 類和對象都是ruby中的第一類值。 應用示例: mongo API for ruby => Mongo::MongoClient # testmongo.rb require 'mongo' require 'pp' include Mongo # the members of replcation-set # test mongodb server version 2.6.0 host = "192.168.11.51" # The port of members # If the port is 27017 by default then otherport don't need to assignment otherport = "" port = otherport.length != 0 ? otherport : MongoClient::DEFAULT_PORT opts = {:pool_size => 5, :pool_timeout => 10} # Create a new connection client = MongoClient.new(host, port, opts) # puts client.class puts client.class.constants puts client.instance_variables puts client.class.instance_methods(false) 分別輸出Constant, Instance Attribute, Instance Method。