笔记一:
代码中包含变量,类和方法,统称为语言构建(language construct)。
# test.rbclass greeting def initialize(text) @text = text end def welcome @text endendmy_obj = greeting.new(hello)puts my_obj.classputs my_obj.class.instance_methods(false) #false means not inheritedputs my_obj.instance_variablesresult =>greetingwelcome@text
总结:
实例方法继承于类,实例变量存在于对象本身。
类和对象都是ruby中的第一类值。
应用示例:
mongo api for ruby => mongo::mongoclient# testmongo.rbrequire 'mongo'require 'pp'include mongo# the members of replcation-set# test mongodb server version 2.6.0host = 192.168.11.51# the port of members# if the port is 27017 by default then otherport don't need to assignmentotherport = port = otherport.length != 0 ? otherport : mongoclient::default_portopts = {:pool_size => 5, :pool_timeout => 10}# create a new connectionclient = mongoclient.new(host, port, opts)# puts client.classputs client.class.constantsputs client.instance_variablesputs client.class.instance_methods(false)
分别输出
constant, instance attribute, instance method
笔记二:动态调用
当你调用一个方法时,实际是给一个对象发送了一条消息。
class myclass def my_method(args) args * 10 endendobj = myclass.newputs obj.my_method(5)puts **puts obj.send(:my_method, 6)
结果:
50**60
可以使用object#send()取代点标记符来调用myclass#my_method()方法:
obj.send(:my_method, 6)
send()方法第一个参数是要发送给对象的消息,可以是符号(:symbol)或字符串,其他参数会直接传递给调用的方法。
可以动态的决定调用哪个方法的技术,成为dynamic dispatch。
笔记三:符号和字符串的区别
1. 符号不可变,可以修改字符串中的字符。
2. 针对符号的操作更快些。
3. 通常符号用来表示事物的名字。
例如:
puts 1.send(:+, 4) => 5string#to_sym(),string#intern() => string to symbolstring#to_s(),string#id2name() => symbol to stringcaoqing.to_sym() => :caoqing:caoqing.to_s() => caoqing
动态派发中使用模式派发(pattern dispatch)的方法。
puts obj.class.instance_methods(true).delete_if{ |method_name| method_name !~ /^my/}result => my_method
笔记四:动态定义
使用module#define_method()方法定义一个方法。
class myclass define_method :my_method do |args| args * 3 endendobj = myclass.newputs obj.my_method(10)
结果:30
单件方法允许给单个对象增加一个方法。singleton methods
# test.rbstr = my name is caoqing.def str.title? self.upcase == selfendputs str.title?puts str.methods.grep(/^title?/)puts str.singleton_methods
结果:
falsetitle?title?
笔记五:
类方法的本质,类是对象,类名是常量。在类上调用方法和对象调用方法一样:
obj.my_methodcla.class_method
duck typing:对象能不能响应方法,可以是普通方法或者单件方法。
类方法的实质就是他们是类的一个单件方法。
def obj.method # method bodyend
obj可以是对象引用,常量类名或self。
类宏(class macro)
ruby对象没有属性,可以使用拟态方法定义属性。
module#attr_*()方法中的一员来定义访问器。类宏不是关键字而是方法。
eigenclass
单件方法按照常规的方法查找在祖先链无法找到保存的地方,obj是对象不能保存,也不能存在于class内,否则所有的实例都可以共享这个方法。
对象拥有一个特有的隐藏类,称为该对象的eigenclass。
进入eigenclass作用域:
class lionfoo.method01foo.method02foo.method03obj.putsname
结果:
lioncatcattigertigerdogdogdog