This article mainly introduces the basic usage of hash in Ruby, including the creation of hashing and the use of some built-in methods, the need of friends can refer to the
A collection of hashing-value pairs, similar to this: "Employee" => "salary". It is similar to an array, except that the index is the type of any object that passes through any key, not an integer index.
Sequential traversal of a hashing or value may appear arbitrary, generally not in the insertion order. If the hash value of the key being accessed does not exist, the method returns nil.
To create a hash:
Using arrays, there are various ways to create hash values. You can create an empty hash of the new class method:
?
You can also use new to create a hash, which is a default value, otherwise it is simply nil:
Copy code code as follows:
months = Hash.new ("month")
Or
months = hash.new "Month"
When accessing any of the hashing, there is a default value, and if the key or value does not exist, accessing the hash table will return the default value:
?
1 2 3 4 5 6 |
#!/usr/bin/ruby months = hash.new ("month") puts "#{months[0]}" puts "#{months[72]}" |
This will produce the following results:
?
1 2 3 4 5 6 7 8 9 |
Month month #!/usr/bin/ruby H = hash["A" =>, "B" => "puts" #{h[' a ']} "puts" #{h[' B ']} " |
This will produce the following results:
?
You can use any Ruby object as a key or value, or even an array, so the following example is a valid
?
Hashing the built-in method:
We need to have a hash object instance call hashing method. As we have seen, the following is the way of the hash object to create an instance:
?
1 2 3 4 5 |
Hash[[key =>|, value]*] or hash.new [or] hash.new (obj) [or] hash.new {|hash, key| block} |
This returns a new hash value with the given object fill. Now using the created object, we can call any available instance methods. For example:
?
1 2 3 4 5 6 7 8 9 10 |
#!/usr/bin/ruby $, = "," months = Hash.new ("month") months = {"1" => "January", "2" => "February"} keys = m Onths.keys puts "#{keys}" |
This will produce the following results:
?