Tutorials for creating and using hashes in Ruby _ruby topics

Source: Internet
Author: User
Tags deprecated hash





A hash is a collection of key-value pairs such as "employee" => "salary". The index of a hash is done by any key of any object type, not an integer index, and the other is similar to an array.



The order in which the hash is traversed by a key or value appears arbitrary and is not usually in the order of insertion. If you try to access the hash through a key that does not exist, the method returns nil.
Create Hash



As with arrays, there are various ways to create hashes. You can create an empty hash from the new class method:


months = Hash.new


You can also use new to create a hash with a default value, and a hash with no default value is nil:


months = Hash.new ("month")
 
or
 
months = hash.new "Month"


When you access any key in the hash with a default value, the access hashes return the default value if the key or value does not exist:


#!/usr/bin/ruby
 
months = hash.new ("month")
 
puts "#{months[0]}" puts
"#{months[72]}"


This will produce the following results:


Month
month
#!/usr/bin/ruby
 
H = hash["A" =>, "B" =>]
 
puts "#{h[' a"]} "
puts" #{h[ ' B ']} '


This will produce the following results:


200


You can use any Ruby object as a key or value, or even use an array, so the following example is a valid instance:


[1, "=>"] "January"


Hashing Built-in method



We need to have an instance of a hash object to invoke the hash method. Here's how to create a Hash object instance:


Hash[[key =>|, value]*] or
 
hash.new [or] hash.new (obj) [or]
 
hash.new {|hash, key| block}


This returns a new hash that is populated with the given object. Now, using the created object, we can invoke any available instance methods. For example:


#!/usr/bin/ruby
 
$, = ","
months = hash.new ("month")
 
months = {"1" => "January", "2" => "February"}
 
keys = Months.keys
 
puts "#{keys}"


This will produce the following results:


2, 1


The following is a public hashing method (assuming that the hash is a hash object):


No. Method & Description
1 hash == other_hash
Check whether the two hashes have the same number of key-value pairs and whether the key-value pairs match each other to determine whether the two hashes are equal.
2 hash. [Key]
Use keys to reference values from the hash. If no key is found, the default value is returned.
3 hash. [Key] = value
Associates the value given by value with the key given by key.
4 hash.clear
Remove all key-value pairs from the hash.
5 hash.default (key = nil)
Returns the default value of hash, or nil if not set by default =. (If the key does not exist in the hash, [] returns a default value.)
6 hash.default = obj
Set the default value for hash.
7 hash.default_proc
If the hash is created from a block, the block is returned.
8 hash.delete (key) [or]
array.delete (key) {| key | block}
Remove key-value pairs from hash by key. If a block is used and no matching key-value pair is found, the result of the block is returned. Compare it with delete_if.
9 hash.delete_if {| key, value | block}
For each block where block is true, remove key-value pairs from the hash.
10 hash.each {| key, value | block}
Iterate over the hash, call the block once for each key, and pass key-value as a two-element array.
11 hash.each_key {| key | block}
Iterate through the hash, calling the block once for each key, passing the key as a parameter.
12 hash.each_key {| key_value_array | block}
Iterate over the hash, call the block once for each key, passing key and value as parameters.
13 hash.each_key {| value | block}
Iterate over the hash, call the block once for each key, and pass value as a parameter.
14 hash.empty?
Checks if the hash is empty (excluding key-value pairs) and returns true or false.
15 hash.fetch (key [, default]) [or]
hash.fetch (key) {| key | block}
Returns a value from the hash with the given key. If no key is found and no other parameters are provided, an IndexError exception is thrown; if default is given, default is returned; if an optional block is specified, the result of the block is returned.
16 hash.has_key? (Key) [or] hash.include? (Key) [or]
hash.key? (key) [or] hash.member? (key)
Checks if the given key exists in the hash and returns true or false.
17 hash.has_value? (Value)
Checks if the hash contains the given value.
18 hash.index (value)
Returns the key in the hash for the given value, or nil if no matching value was found.
19 hash.indexes (keys)
Returns a new array consisting of the values of the given key. Keys that are not found will be inserted with default values. This method is deprecated, use select.
20 hash.indices (keys)
Returns a new array consisting of the values of the given key. Keys that are not found will be inserted with default values. This method is deprecated, use select.
21 hash.inspect
Returns a printed string version of the hash.
22 hash.invert
Create a new hash and invert the keys and values in the hash. That is, in the new hash, the keys in the hash will become values and the values will become keys.
23 hash.keys
Create a new array with the keys in the hash. / td>
24 hash.length
Returns the size or length of the hash as an integer.
25 hash.merge (other_hash) [or]
hash.merge (other_hash) {| key, oldval, newval | block}
Returns a new hash containing the contents of hash and other_hash, rewriting the key-value pairs in hash that have duplicate keys with other_hash.
26 hash.merge! (Other_hash) [or]
hash.merge! (other_hash) {| key, oldval, newval | block}
Same as merge, but the hash has actually changed.
27 hash.rehash
Rebuilds the hash based on the current value of each key. If the value changes after inserting, the method re-indexes the hash.
28 hash.reject {| key, value | block}
Create a new hash for each key-value pair whose block is true.
29 hash.reject! {| Key, value | block}
Same as reject, but the hash has actually changed.
30 hash.replace (other_hash)
Replace the contents of hash with the contents of other_hash.
31 hash.select {| key, value | block}
Returns a new array of key-value pairs in a hash whose block returns true.
32 hash.shift
Removes a key-value pair from the hash and returns the key-value pair as a two-element array.
33 hash.size
Returns the size or length of the hash as an integer.
34 hash.sort
Converts a hash to a two-dimensional array containing an array of key-value pairs, and then sorts them.
35 hash.store (key, value)
Stores a key-value pair in a hash.
36 hash.to_a
Create a two-dimensional array from the hash. Each key-value pair is converted into an array, all of which are stored in an array.
37 hash.to_hash
Returns hash (self).
38 hash.to_s
Converts a hash to an array, and then converts the array to a string.
39 hash.update (other_hash) [or]
hash.update (other_hash) {| key, oldval, newval | block}
Returns a new hash containing the contents of hash and other_hash, rewriting the key-value pairs in hash that have duplicate keys with other_hash.
40 hash.value? (Value)
Checks if the hash contains the given value.
41 hash.values
Returns a new array containing all the values of the hash.
42 hash.values_at (obj, ...)
Returns a new array containing the values in the hash associated with the given key.


















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.