A brief summary of the basic operation methods of hash hash structure in Ruby _ruby special topics

Source: Internet
Author: User
Tags arrays hash


About hashing
Let's take a look at the basic idea of hashing:
To set the number of objects to be stored in NUM, then we use Len Memory units to store them (len>=num); With the keyword of each object ki as the independent variable, a function h (KI) is used to map the memory address of Ki, that is, the subscript of Ki, the element content of the Ki object is deposited in this address. This is the basic idea of hash.
Why do you use a function to map their address cells?
Let's say I'm going to store 4 elements 13 7 14 11
Obviously, we can use arrays to save. namely: a[1] = 13; A[2] = 7; A[3] = 14; A[4] = 11;
Of course, we can also use hash to save. A simple hash store is given below:
Let's determine that function first. We use H (ki) = ki%5;
For the first element h (13) = 13%5 = 3; That is, 13 subscript 3; that is hash[3] = 13;
For the second element h (7) = 7% 5 = 2; That is to say 7 subscript 2; ie hash[2] = 7;
Similarly, hash[4] = 14; HASH[1] = 11;
Now I want you to look up 11 to see if this element exists. What would you do? Of course, for an array, that's quite simple, A for loop is OK.
Which means we're looking for 4 times.
Let's take a look at the hash below.
First, we're going to look for the element 11 to map out the address cell where it is in just the function. That is, h (11) = 11%5 = 1. Now let's compare the hash[1]?=11, the problem is very simple. That means we've been looking for it 1 times. This is the beauty of hash, by making a rule (function) to map out its address, the data can be through this rule to find its memory address.



The hash structure in Ruby
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), 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, we need to process , as follows (if all the data types in the hash are the same, do not do 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)           #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))


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



Deep Excavation
1. Treat the hash as an array:
the value of the keys and values method in the hash is an array, so we can use the array method to manipulate them:


H1 = {1=> ' one ', 2=> ' two ', 3=> ' three ',4=> ' four '}
h2 = {1=> ' One ', 3=> ' two ', 4=> ' four ',5=> ' fi ve '}
 
p (H1.keys & H2.keys) p (
h1.values & H2.values) p (
H1.keys+h2.keys) p
(h1.values-h2.value s)
P ((H1.keys << h2.keys))
p ((H1.keys << h2.keys). Flatten)


Results:


[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. The difference between appending and continuous:
+: Add elements to an array, create a new array
<<: To add elements to a data, directly manipulate the original array, when the new element added to an array is also an array, the new element as the last element of the array:


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


Results:


[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.