The basic operation method of hash hash type in Ruby Summary _ruby special topic

Source: Internet
Author: User


1. Create a hash: just like creating an array, we can create a hash instance from the hash class:


H1 = hash.new #default is nil
h2 = Hash.new ("This is the My-my-a-hash instance") #The default value is "This is me-a-my-a-hash instance":


The above two examples create an empty hash instance. A hash object always has a default value-because if the specified index (key) is not found in a hash object, the default value is returned.
Once the hash object is created, we can add/remove items like an array. The only difference is that an index in an array can only be an integer, whereas in a hash the index (key) can be any type of object and unique data:


h2["one"] = "Beijing"
h2["two"] = "Shanghai"
h2["three"] = "Shenzhen"
h2["four"] = "Guangzhou"


Note: If you use the same key when assigning to a hash, then the value behind will overwrite the previous value. In addition, Ruby provides a convenient way to create and initialize hashes by simply adding a => symbol to the key followed by a value. Each key-value is separated by commas. The whole is then enclosed in curly braces:


H2 = {"One
" => "Beijing", "
Two" => "Shanghai",
"three" => "Shenzhen",
"four" => "Guangzhou" 
}



2. Access to hash value via index:
to get a value, you can use the following method:


Puts h2["one"]    #=> "Beijing"


If the specified key does not exist, the default value is returned (as mentioned previously). In addition, we can use the default method to get defaults, set the default value with the Default+= method


  Puts H1.default
  H1.default = "This was set value method"



3. Copy hash:
As with arrays, we can assign a hash variable to another hash variable, all of which refer to the same hash, so if one of the values changes, the other value will also change:


  H3 = H2
  h3["one" = "Xi ' an"
  puts H h2["one"]    #=> "Xi ' an"


Sometimes we do not want the above situation, namely: modified one of the value of the other also followed the modification, we can use the Clone method make a new copy


  h4 = H2.clone
  h4["One" = "Dalian"
  puts h2["one"]       #=> "Xi ' an" (i.e. value not modified)



4.Hash Sort:
when we need to sort the hash, you can't use the Sort method as simple as an array, because the data types in the array are the same (integer), and the data types in the hash may not be exactly the same, such as integer types and string types that can't be sorted together, and we need to process them. as follows (if the data types in the hash are all the same, you can do this without doing the following):


  def sorted_hash (Ahash) return
    ahash.sort{
      |a,b| a.to_s <=> b.to_s      
    }
  end
h1 = {1=> ' One ', 2 => ' two ', 3=> ' three '} h2 = {6=> ' Six ', 5=> ' five '
, 4=> ' four '}
h3 = {' One ' => ' A ', ' two ' => ' B ', ' Three ' => ' C '}
h4 = H1.merge (H2)      #合并hash
h5 = H1.merge (h3)
def sorted_hash (Ahash)
 return ahash.sort{|a,b| a.to_s <=> b.to_s}
end
P (H4) p     
(H4.sort) p (h5) p
(Sorted_hash (h5))


Results


{5=> "Five", 6=> "six", 1=> "one", 2=> "two", 3=> "three", 4=> "four"}
[[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "Five"], [6, "six"
]] {"Two" => "B", "three" => "C", 1=> "one", 2=> "two", "One" => "A", 3=> "three"}
[[1, "one"], [2, "two"], [3, "three"], ["One", "A"], ["Three", "C"], ["Two", "B"]]



In fact, the hash sort method is to convert a hash object to an array of [Key,value] as a single element, and then sort by the array's sort method.



5.Hash Class Common methods:


Method

Description

Size ()

return Hash the length of the object

Length ()

return Hash the length of the object

Include? (key)

judge the specified Hash object contains the specified Key

Has_key? (key)

judge the specified Hash object contains the specified Key

Delete (key)

Remove Hash object is specified in the Key the corresponding element

Keys ()

returns the Hash all of the objects Key Array of Components

VALUES ()

returns the Hash all of the objects value Array of Components


e.g.




  Student = {
     "name" => "Steve",
     "age" =>,
     "Gender" => "Male"
    }  
  p Student.keys              #=> ["Name", "Gender", "Age"]
  P student.values            #=> ["Steve", "male",]
  puts Student.include? (" Age ")       #=> true
  puts Student.size             #=> 3
  student.delete (" Gender ")
  puts Student.has_ Key? ("Gender")       #=>false
  puts Student.size             #=>2


6.Hash Conversion Usage
when dealing with nesting of several layers of hash, always feel very confused, read, modify the cumbersome. So think of converting hash to object, directly generate key Get/set method, the code is as follows:


 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


Using 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 #




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.