加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Ruby元编程基础学习笔记整理

发布时间:2020-05-25 11:19:07 所属栏目:Python 来源:互联网
导读:笔记一:代码中包含变量,类和方法,统称为语言构建(languageconstruct)。#test.rb

笔记一:
代码中包含变量,类和方法,统称为语言构建(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

笔记二:动态调用
当你调用一个方法时,实际是给一个对象发送了一条消息。

class MyClass
 def my_method(args)
  args * 10
 end
end
obj = MyClass.new

puts 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) => 5
String#to_sym(),String#intern() => string to symbol
String#to_s(),String#id2name() => symbol to string
"caoqing".to_sym() => :caoqing
:caoqing.to_s() => "caoqing"

动态派发中使用模式派发(pattern dispatch)的方法。

puts obj.class.instance_methods(true).delete_if{ |method_name| method_name !~ /^my

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读