Summary of basic operation methods of hash type in Ruby

Time:2021-11-23

1. Create hash:Just like creating arrays, 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, we modify one of the values and the other. We can use the clone method to make a new copy

?
1
2
3
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

6. Conversion and use of hash
When dealing with nested hashes, I always feel confused, and it is troublesome to read and modify them. Therefore, I want to convert the hash into an object and directly generate the get / set method of the key. The code is as follows:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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

?
1
2
3
4
5
6
7
8
9
10
11
12
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"}}