方法 |
說明 |
size() |
返回Hash對(duì)象的長(zhǎng)度 |
length() |
返回Hash對(duì)象的長(zhǎng)度 |
include?(key) |
判斷指定的Hash對(duì)象是否包含指定的key |
has_key?(key) |
判斷指定的Hash對(duì)象是否包含指定的key |
delete(key) |
刪除Hash對(duì)象中指定key的對(duì)應(yīng)元素 |
keys() |
返回由Hash對(duì)象中全部key組成的數(shù)組 |
values() |
返回由Hash對(duì)象中全部value組成的數(shù)組 |
student = { "name" => "Steve", "age" => 22, "Gender" => "male" } p student.keys #=> ["name", "Gender", "age"] p student.values #=> ["Steve", "male", 22] puts student.include?("age") #=> true puts student.size #=> 3 student.delete("Gender") puts student.has_key?("Gender") #=>false puts student.size #=>2
6.Hash的轉(zhuǎn)換使用
在處理嵌套了幾層的hash時(shí),總是感覺很混亂,讀取、修改時(shí)都很麻煩。因此想到把hash轉(zhuǎn)換為對(duì)象,直接生成key的get/set方法,代碼如下:
class HashObj class self def load_from_hash(hash) if hash.instance_of? Hash obj = HashObj.new hash.each{|k,v| obj.send :def_sget_method,k,HashObj.load_from_hash(v)} obj elsif hash.instance_of? Array hash.map{|m| HashObj.load_from_hash(m) } else hash end end end def attributes hash = {} @@reg ||= /=/ self.singleton_methods.reject{|x| @@reg =~ x.to_s}.each do |m| v = self.send(m) if v.instance_of? HashObj real_v = v.attributes elsif v.instance_of? Array real_v = [] v.each do |l| if l.instance_of? HashObj real_v l.attributes else real_v l end end else real_v = v end hash[m] = real_v end hash end protected def def_sget_method(name,val) self.instance_variable_set "@#{name}",val self.define_singleton_method "#{name}=" do |n_val| instance_variable_set "@#{name}",n_val end self.define_singleton_method name do instance_variable_get "@#{name}" end end end
使用demo
hash = {name:'jack',age:22,phone:['61900871','8787876'], basic_info:{country:'USA',city:'New York'}} obj = HashObj.load_from_hash hash obj.name #'jack' obj.age #22 obj.phone #['61900871','8787876'] obj.basic_info #HashObj:0x007f9eda02b360 @country="USA", @city="New York"> obj.basic_info.country #'USA' obj.attributes == hash #true obj.age = 30 obj.attributes #{:name=>"jack", :age=>30, :phone=>["61900871", "8787876"], # :basic_info=>{:country=>"USA", :city=>"New York"}}
標(biāo)簽:宜春 六安 鄂州 河北 石嘴山 淄博 松原 自貢
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Ruby中的Hash哈希類型基本操作方法小結(jié)》,本文關(guān)鍵詞 Ruby,中的,Hash,哈希,類型,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。