11 questions about Hash in Ruby and rubyhash

Source: Internet
Author: User
Tags rehash

11 questions about Hash in Ruby and rubyhash

Recently I am studying Rails because the java language I learned is the Getting Started language. a little uncomfortable. in particular, Ruby's Hash. however, you will be able to think about it in detail. basically, all are passed Key-Value. there is no big problem except that it is not suitable for writing at the beginning. this is a log I saw on the Internet.

1. How to Create a Hash?

Copy codeThe Code is as follows:
X = Hash. new
X = {}
X = {: a => 1,: B => 2}

These are all Hash creation methods.
The first and second are the same, indicating that an empty Hash is created.
The third indicates the created Hash, which has two pairs of key/value.

2. What types of Hash keys are used?

It can be any target, such:

Copy codeThe Code is as follows:
Irb (main): 002: 0> x = {}
=> {}
Irb (main): 003: 0> x [1] = 2
=> 2
Irb (main): 004: 0> x ["a"] = "B"
=> "B"
Irb (main): 005: 0> x [: z] = 100
=> 100
Irb (main): 006: 0> x [[1, 2, 3] = [4, 5, 6]
=> [4, 5, 6]
Irb (main): 007: 0> x
==>{ "A" => "B", [1, 2, 3] => [4, 5, 6], 1 => 2,: z => 100}

Note:
(1) Any target, including arrays and Hash, can be keys.
(2) When using a character as the Key, it is best to use the corresponding symbol. For example, the key "a" can be replaced by:. This is because each character "a" is a target, and a is unique,

Saves more memory.

3. How do I assign a default value to Hash?

Copy codeThe Code is as follows:
Irb (main): 003: 0> x = Hash. new ([])
=> {}
Irb (main): 004: 0> x [: a]
=> []

Creates a Hash. Its default value is an empty array [].
Then access x [: a]. Although this key is not defined in advance, there are still default values.

Note: The default value assigned by this method points to the same target, which changes and affects all default values.
Copy codeThe Code is as follows:
Irb (main): 005: 0> x [: a] <1
=> [1]
Irb (main): 006: 0> x [: B]
=> [1]

To ensure that each key corresponds to a unique default value, create a Hash as follows:
Copy codeThe Code is as follows:
Irb (main): 007: 0> y = Hash. new do | h, k | h [k] = [] end
=> {}

Let's take a look:
Copy codeThe Code is as follows:
Irb (main): 009: 0> y [: a] <1
=> [1]
Irb (main): 010: 0> y [: B]
=> []

Changing a value does not affect other default values.

4. How to traverse Hash?
Copy codeThe Code is as follows:
Irb (main): 018: 0 * x = {1 => 2, 3 => 4, 5 => 6}
==>{ 5 => 6, 1 => 2, 3 => 4}

Irb (main): 019: 0> x. each do | k, v | puts "# {k }#{ v}" end
5 6
1 2
3 4
==>{ 5 => 6, 1 => 2, 3 => 4}

Use the each method of Hash.

5. How to traverse the Key and Value of Hash?
Copy codeThe Code is as follows:
Irb (main): 020: 0> x. keys. each do | k | puts k end

Irb (main): 021: 0> x. values. each do | v | puts v end

Use the Hash keys and values methods to return an array.

Of course, you can also use the each_key and each_value methods, as the name implies, to traverse the key and value.
Copy codeThe Code is as follows:
Irb (main): 016: 0> x. each_key do | s | puts s end
1
3
==>{ 1 => 2, 3 => 4}
Irb (main): 017: 0> x. each_value do | s | puts s end
2
4
==>{ 1 => 2, 3 => 4}

6. can Hash be sort?

Ruby's hash can actually be sort, and returns a two-dimensional array after sort.
Copy codeThe Code is as follows:
Irb (main): 027: 0> x
==>{ 5 => 6, 1 => 2, 3 => 4}

Irb (main): 028: 0> x. sort
=> [[1, 2], [3, 4], [5, 6]

In addition, ruby has the OrderedHash class, which allows Hash elements to be sort in the insert order, similar to the ability of arrays.

7. how to add and delete elements from the Hash?

Add elements to directly define Key/Value:
Copy codeThe Code is as follows:
Irb (main): 040: 0> x [7] = 8
=> 8

Irb (main): 041: 0> x
==>{ 5 => 6, 1 => 2, 7 => 8, 3 => 4}

Delete an element using the delete method. The parameter is the Key to be deleted:

Copy codeThe Code is as follows:
Irb (main): 042: 0> x. delete (7)
=> 8

Irb (main): 043: 0> x
==>{ 5 => 6, 1 => 2, 3 => 4}

You can also use delete_if to delete the Hash element with conditions. For example, delete all keys greater than 3:

Copy codeThe Code is as follows:
Irb (main): 074: 0 * x. delete_if do | k, v | k> 3 end
==>{ 1 => 2, 3 => 4}

8. How do I find Hash elements?

Use has_key? And has_value? To determine whether there is a corresponding key and value:

Copy codeThe Code is as follows:
Irb (main): 052: 0> x. has_key? 1
=> True

Irb (main): 053: 0> x. has_value? 4
=> True

Irb (main): 054: 0> x. has_key? 9
=> False

Considering the default value, the if hash [: key] cannot be used for determination. For example:

Copy codeThe Code is as follows:
Irb (main): 055: 0> y = Hash. new (9)
=> {}

Irb (main): 056: 0> y. has_key? :
=> False

Irb (main): 057: 0> puts 1 if y [: a]
1
=> Nil

Other search methods include find and select. For example, find all elements whose keys are greater than 2:

Copy codeThe Code is as follows:
Irb (main): 038: 0> x. select do | k, v | k> 2 end
=> [[5, 6], [3, 4]

9. Can I reverse Hash?

The answer is yes. Use the invert method:

Copy codeThe Code is as follows:
Irb (main): 011: 0 * x = {1 => 2, 3 => 4, 5 => 6}
==>{ 5 => 6, 1 => 2, 3 => 4}

Irb (main): 012: 0> x. invert
==>{ 6 => 5, 2 => 1, 4 => 3}

10. How to convert Hash and array?

It is easy to convert Hash to array:

Copy codeThe Code is as follows:
Irb (main): 020: 0> x. to_a
=> [[5, 6], [1, 2], [3, 4]

It is troublesome to convert an array to Hash. You can write the to_hash method yourself:

Copy codeThe Code is as follows:
Irb (main): 023: 0> class Array
Irb (main): 024: 1> def to_hash
Irb (main): 025: 2> unless size % 2 = 0
Irb (main): 026: 3> raise "array with odd number of elements"
Irb (main): 027: 3> end
Irb (main): 028: 2> hash = Hash. new
Irb (main): 029: 2> 0. step (size-1, 2) {| x | hash [self [x] = self [x + 1]}
Irb (main): 030: 2> hash
Irb (main): 031: 2> end
Irb (main): 032: 1> end
=> Nil

Irb (main): 033: 0> x = [1, 2, 3, 4, 5, 6]
=> [1, 2, 3, 4, 5, 6]

Irb (main): 034: 0> x. to_hash
==>{ 5 => 6, 1 => 2, 3 => 4}

11. What is the Hash value loss behavior?

If the Hash Key is modified at any time (remember that the Key is a target including an array), the value is lost.

Copy codeThe Code is as follows:
Irb (main): 001: 0> h = Hash. new
=> {}
Irb (main): 002: 0> x = [1, 2, 3]
=> [1, 2, 3]
Irb (main): 003: 0> h [x] = 4
=> 4
Irb (main): 004: 0> h [x]
=> 4
Irb (main): 005: 0> x <4
=> [1, 2, 3, 4]
Irb (main): 006: 0> h [x]

If the Value of the key x is modified, the Value corresponding to the key is lost.
The solution is rehash. You must rehash the Key value at any time.

Copy codeThe Code is as follows:
Irb (main): 007: 0> h. rehash
==>{ [1, 2, 3, 4] => 4}
Irb (main): 008: 0> h [x]
=> 4

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.