A summary of the basic operation methods of the Hash structure in Ruby, rubyhash

Source: Internet
Author: User

A summary of the basic operation methods of the Hash structure in Ruby, rubyhash

About hash
First, let's take a look at the basic ideas of Hash:
If the number of objects to be stored is num, we will use len memory units to store them (len> = num). The keyword of each object ki is used as the independent variable, use a function h (ki) to map the memory address of the ki, that is, the subscript Of The ki, and store all the elements of the ki object in this address. This is the basic idea of Hash.
Why map their address units with a function?
Suppose now I want to store 4 elements 13 7 14 11
Obviously, we can use Arrays for storage. That is, a [1] = 13; a [2] = 7; a [3] = 14; a [4] = 11;
Of course, we can also use Hash for storage. Below is a simple Hash Storage:
Determine the function first. We use h (ki) = ki % 5;
For the first element h (13) = 13% 5 = 3; that is, the subscript of 13 is 3; that is, Hash [3] = 13;
For the second element h (7) = 7% 5 = 2; that is, the subscript of 7 is 2; that is, Hash [2] = 7;
Similarly, Hash [4] = 14; Hash [1] = 11;
Now I want you to check whether the element 11 exists. What would you do? Of course, for arrays, that is quite simple. A for loop is enough.
That is to say, we need to find it four times.
Next we will use Hash to find out.
First, we will map the element 11 to the address unit in the previous function. That is, h (11) = 11% 5 = 1. Next we will compare Hash [1]? = 11. This problem is very simple. That is to say, we searched for it once. This is the magic of Hash. By setting a rule (function) to map its address, the data will be able to find its memory address through this rule.

Hash structure in Ruby
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" (the I. e. 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

 
Deep Mining
1. Treat Hash as an array:
The return values of the keys and values methods in Hash are all an array, so we can use the array method to operate on them:

h1 = {1=>'one', 2=>'two', 3=> 'three',4=> 'four'}h2 = {1=>'one', 3=>'two', 4=> 'four',5=> 'five'} p( h1.keys & h2.keys )p( h1.values & h2.values )p( h1.keys+h2.keys )p( h1.values-h2.values )p( (h1.keys << h2.keys) )p( (h1.keys << h2.keys).flatten)

Result:

[1, 3, 4]["one", "two", "four"][1, 2, 3, 4, 5, 1, 3, 4]["three"][1, 2, 3, 4, [5, 1, 3, 4]][1, 2, 3, 4, 5, 1, 3, 4]

 
2. Differences between append and continuity:
+: Add elements to an array and create a new array.
<: Add an element to a data array and operate the original array directly. When the new element added to an array is also an array, the new element serves as the last element of the array:

  a=[1,2,3]  b=[4,5,6]   p(a+b)  p(a<<b)

Result:

[1, 2, 3, 4, 5, 6][1, 2, 3, [4, 5, 6]]     #[1, 2, 3, [4, 5, 6]].flatten =>[1, 2, 3, 4, 5, 6]

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.