Summary of basic operation methods of hash structure in Ruby

Time:2021-11-21

About hash
Let’s first understand the basic idea of hash:
Set the number of objects to be stored as num, then we use len memory units to store them (len > = Num); Take the keyword of each object ki as the argument, use a function H (KI) to reflect the memory address of Ki, that is, the subscript of Ki, and store all the element contents of Ki object in this address. This is the basic idea of hash.
Why use a function to map out their address units?
Suppose now I want to store four elements 13 7 14 11
Obviously, we can use arrays to store. That is: a [1] = 13; a[2] = 7; a[3] = 14; a[4] = 11;
Of course, we can also use hash to save. Here is a simple hash storage:
Let’s 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 find 11 whether this element exists. What would you do? Of course, for arrays, it’s quite simple, just a for loop.
That means we have to find it four times.
Let’s use hash to find it.
First, we substitute the element 11 to be found into the function just now to map its address unit. That is, H (11) = 11% 5 = 1. Let’s compare hash [1]= 11. The problem is very simple. That means we looked for it once. This is the beauty of hash. By formulating a rule (function) to map its address, data can find its memory address through this rule.

Hash structure in Ruby
1. Create hash: just like creating an array, we can create a hash instance through the hash class:

?
1
2
h1 = Hash.new                         #The default value is nil
h2 = Hash.new(“This is my first hash instance”) #The default value is "this is my first hash instance":

Both of the above 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 will be returned.
After creating the 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 in the hash, the index (key) can be any type of object and unique data:

?
1
2
3
4
h2["one"] = "Beijing"
h2["two"] = "Shanghai"
h2["three"] = "Shenzhen"
h2["four"] = "Guangzhou"

Note: if the same key is used when assigning a value to hash, the following value will overwrite the previous value. In addition, ruby also provides a convenient method to create and initialize hash. You only need to add a = > symbol after the key and a value. Each key value pair is separated by a comma. Then enclose the whole with braces:

?
1
2
3
4
5
6
h2 = {
"one" => "Beijing",
"two" =>"Shanghai",
"three" =>"Shenzhen",
"four" =>"Guangzhou"
}

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

?
1
puts h2[“one”]       #=>"Beijing"

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

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

3. Copy hash:
Like arrays, we can assign a hash variable to another hash variable. They all refer to the same hash. Therefore, if the value of one of them changes, the value of the other will also change:

?
1
2
3
h3 = h2
H3 ["one"] = "Xi'an"
puts h h2[“one”]        #=>"Xi'an"

Sometimes we don’t want the above situation to happen, that is, if we modify the value of one of them and the other, we can use the clone method to make a new

?
1
2
3
4
copy
    h4 = h2.clone
    H4 ["one"] = "Dalian"
    puts h2[“one”]              #=>"Xi'an" (i.e. value not modified)

4. Hash sorting:
When we need to sort the hash, we can’t simply use the sort method like the 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. For example, integer types and string types can’t be sorted together. At this time, we need to deal with it, as follows (if the data types in the hash are all the same, the following processing may not be performed):
      

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)           #Merge 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))

result:

?
1
2
3
4
{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 into an array with [key, value] as a single element, and then sort it with the sort method of the array.
 
5. Common methods of hash class:

method

explain

size()

Returns the length of the hash object

length()

Returns the length of the hash object

include?(key)

Judge whether the specified hash object contains the specified key

has_key?(key)

Judge whether the specified hash object contains the specified key

delete(key)

Delete the corresponding element of the specified key in the hash object

keys()

Returns an array of all keys in the hash object

values()

Returns an array of all values in a hash object

e.g.
       

 

?
1
2
3
4
5
6
7
8
9
10
11
12
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 excavation
1. Treat hash as an array:

The return values of the keys and values methods in hash are an array, so we can use the array method to operate on them:

?
1
2
3
4
5
6
7
8
9
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
2
3
4
5
6
[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. Difference between addition and continuity:
+: add elements to an array to create a new array
< <: add an element to a data and directly operate the original array. When the new element added to an array is also an array, the new element is the last element of the array:

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

result:

?
1
2
[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]