Ruby元編程基礎學習筆記整理,ruby學習筆記

來源:互聯網
上載者:User

Ruby元編程基礎學習筆記整理,ruby學習筆記

筆記一:
代碼中包含變數,類和方法,統稱為語言構建(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 string"caoqing".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 << obj codeend

如果想擷取eigenclass的引用,則可以在離開該範圍時返回self:

附錄:
類變數,執行個體變數,類方法,執行個體方法區別
@@                            :var類變數
@                            :執行個體變數
self(?clas,::).method        :類方法
method                        :執行個體方法

# test.rbclass Foo @@var = "lion" def self.method01  puts "cat"  @name = "cat"  @@var = "cat"  puts @name end def self.method02  puts "tiger"  @name = "tiger"  @@var = "tiger"  puts @name end def self.method03  puts "dog"  @name = "dog"  @@var = "dog"  puts @name end def putsname  puts @name  puts @@var endendobj = Foo.new# obj.method01   => (NoMethodError)obj.putsname   => lionFoo.method01Foo.method02Foo.method03obj.putsname

結果:

lioncatcattigertigerdogdogdog

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.