Ruby元编程小结(一)

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。


你可能感兴趣的:(Ruby元编程小结(一))