Ruby對(duì)象操作方法探討
有些剛剛學(xué)習(xí)編程的人員見到Ruby這個(gè)詞的是很,可能會(huì)很迷茫,不知道這是個(gè)什么東西。其實(shí)它是一種解釋型編程語言,能夠幫助我們簡(jiǎn)便的完成許多操作。比如Ruby對(duì)象操作等等。#t#
Ruby不僅可以打開一個(gè)類,而且可以打開一個(gè)對(duì)象,給這個(gè)對(duì)象添加或定制功能,而不影響其他對(duì)象:
- a = "hello"
- b = "goodbye"
- def b.upcase
- gsub(/(.)(.)/)($1.upcase + $2)
- end
- puts a.upcase #HELLO
- puts b.upcase #GoOdBye
我們發(fā)現(xiàn)b.upcase方法被定制成我們自己的了。如果想給一個(gè)對(duì)象添加或定制多個(gè)功能,我們不想多個(gè)def b.method1 def b.method2這么做我們可以有更模塊化的Ruby對(duì)象操作方式:
- 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
這個(gè)class被叫做singleton class,因?yàn)檫@個(gè)class是針對(duì)b這個(gè)對(duì)象的。和設(shè)計(jì)模式singleton object類似,只會(huì)發(fā)生一次的東東我們叫singleton.
self 給你定義的class添加行為
- class TheClass
- class << self
- def hello
- puts "hello!"
- end
- end
- end
- TheClass.hello #hello!
self修改了你定義class的class,這是個(gè)很有用的技術(shù),他可以定義class級(jí)別的helper方法,然后在這個(gè)class的其他的定義中使用。下面一個(gè)Ruby對(duì)象操作列子定義了訪問函數(shù),我們希望訪問的時(shí)候把成員數(shù)據(jù)都轉(zhuǎn)化成string,我們可以通過這個(gè)技術(shù)來定義一個(gè)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對(duì)象操作給你的對(duì)象添加行為,module里面的方法變成了對(duì)象里面的實(shí)例方法:
- 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
以上就是對(duì)Ruby對(duì)象操作的一些使用方法介紹。