Summary of basic operation methods for Hash types in Ruby, rubyhash

Source: Internet
Author: User

Summary of basic operation methods for Hash types in Ruby, rubyhash

1. Create a hash:Just like creating an array, we can create a Hash instance using the Hash class:

H1 = Hash. new # default value: nilh2 = Hash. new ("This is my first hash instance") # default value: "This is my first hash instance ":

In the preceding two examples, an empty Hash instance is created. 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.
After creating a Hash object, we can add/delete items to it like an array. The only difference is that the index in the array can only be an integer, while the index (key) in the Hash can be any type of object and unique data:

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

Note: If the same key is used when assigning values to Hash, the subsequent values overwrite the previous values. In addition, Ruby also provides a convenient method for creating and initializing Hash. You only need to add a => symbol and a value after the key. Each key-value pair is separated by a comma. Then it is enclosed in braces:

H2 = {"one" => "Beijing", "two" => "Shanghai", "three" => "Shenzhen", "four" => "Guangzhou "}

 
2. Access the Hash value through the index:
To obtain a value, use the following method:

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

If the specified key does not exist, the default value is returned (as mentioned earlier ). In addition, we can use the default method to obtain the default value and use the default + = method to set the default value.

    puts h1.default    h1.default += “This is set value method”

 
3. Copy Hash:
Like an array, we can allocate a Hash variable to another hash variable. They all reference 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 don't want the above situation to happen, that is, after modifying one of the values, the other is also modified. We can use the clone method to make a new copy.

H4 = h2.clone h4 ["one"] = "Dalian" puts h2 ["one"] # => "Xi 'an" (I. e. the value is not modified)

 
4. Hash Sorting:
When we need to sort the Hash, we cannot simply use the sort method as the array, because the data types in the array are the same (integer), and the data types in the Hash may not be the same, if the integer and string types cannot be sorted together, we need to process them as follows (if all the data types in Hash are the same, we can not process them as follows ):

Def sorted_hash (aHash) return aHash. sort {| a, B |. to_s <=> B. to_s} Endh1 = {1 => 'one', 2 => 'two', 3 => 'three '} h2 = {6 => 'six ', 5 => 'five', 4 => 'four'} h3 = {'one' => 'A', 'two' => 'B ', 'Three '=> 'C'} h4 = h1.merge (h2) # merge hashh5 = h1.merge (h3) def sorted_hash (aHash) return aHash. sort {| a, B |. to_s <=> B. to_s} endp (h4) p (h4.sort) p (h5) p (sorted_hash (h5 ))

Result

{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 sort method of Hash is to convert a Hash object to an array with [key, value] as a single element, and then sort it using the sort method of the array.

5. Common Hash methods:

Method

Description

Size ()

Returns the length of the Hash object.

Length ()

Returns the length of the Hash object.

Include? (Key)

Determines whether the specified Hash object contains the specified key.

Has_key? (Key)

Determines whether the specified Hash object contains the specified key.

Delete (key)

Deletes the corresponding element of the specified key in the Hash object.

Keys ()

Returns an array consisting of all keys in the Hash object.

Values ()

Returns an array composed of all values in the Hash object.


E.g.

  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. Use Hash Conversion
When several layers of hash are nested, it is always confusing and troublesome to read and modify. Therefore, we want to convert the hash into an object and directly generate the get/set Method of the key. 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 endend

Use demo

hash = {name:'jack',age:22,phone:['61900871','8787876'],    basic_info:{country:'USA',city:'New York'}}obj = HashObj.load_from_hash hashobj.name #'jack'obj.age  #22obj.phone #['61900871','8787876']obj.basic_info #<HashObj:0x007f9eda02b360 @country="USA", @city="New York">obj.basic_info.country #'USA'obj.attributes == hash #trueobj.age = 30obj.attributes #{:name=>"jack", :age=>30, :phone=>["61900871", "8787876"],# :basic_info=>{:country=>"USA", :city=>"New York"}}

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.