Ruby對象操作方法探討
有些剛剛學習編程的人員見到Ruby這個詞的是很,可能會很迷茫,不知道這是個什么東西。其實它是一種解釋型編程語言,能夠幫助我們簡便的完成許多操作。比如Ruby對象操作等等。#t#
Ruby不僅可以打開一個類,而且可以打開一個對象,給這個對象添加或定制功能,而不影響其他對象:
- a = "hello"
- b = "goodbye"
- def b.upcase
- gsub(/(.)(.)/)($1.upcase + $2)
- end
- puts a.upcase #HELLO
- puts b.upcase #GoOdBye
我們發現b.upcase方法被定制成我們自己的了。如果想給一個對象添加或定制多個功能,我們不想多個def b.method1 def b.method2這么做我們可以有更模塊化的Ruby對象操作方式:
- b = "goodbye"
- class << b
- def upcase # create single method
- gsub(/(.)(.)/) { $1.upcase + $2 }
- end
- def upcase!
- gsub!(/(.)(.)/) { $1.upcase + $2 }
- end
- end
- puts b.upcase # GoOdBye
- puts b # goodbye
- b.upcase!
- puts b # GoOdBye
這個class被叫做singleton class,因為這個class是針對b這個對象的。和設計模式singleton object類似,只會發生一次的東東我們叫singleton.
self 給你定義的class添加行為
- class TheClass
- class << self
- def hello
- puts "hello!"
- end
- end
- end
- TheClass.hello #hello!
self修改了你定義class的class,這是個很有用的技術,他可以定義class級別的helper方法,然后在這個class的其他的定義中使用。下面一個Ruby對象操作列子定義了訪問函數,我們希望訪問的時候把成員數據都轉化成string,我們可以通過這個技術來定義一個Class-Level的方法accessor_string:
- class MyClass
- class << self
- def accessor_string(*names)
- names.each do |name|
- class_eval <<-EOF
- def #{name}
- @#{name}.to_s
- end
- EOF
- end
- end
- end
- def initialize
- @a = [ 1, 2, 3 ]
- @b = Time.now
- end
- accessor_string :a, :b
- end
- o = MyClass.new
- puts o.a # 123
- puts o.b # Fri Nov 21
09:50:51 +0800 2008
通過extend module的Ruby對象操作給你的對象添加行為,module里面的方法變成了對象里面的實例方法:
- Ruby代碼
- module Quantifier
- def any?
- self.each { |x| return true
if yield x }- false
- end
- def all?
- self.each { |x| return false
if not yield x }- true
- end
- end
- list = [1, 2, 3, 4, 5]
- list.extend(Quantifier)
- flag1 = list.any? {|x| x > 5 } # false
- flag2 = list.any? {|x| x >= 5 } # true
- flag3 = list.all? {|x| x <= 10 } # true
- flag4 = list.all? {|x| x % 2 == 0 } # false
以上就是對Ruby對象操作的一些使用方法介紹。