11 questions about hash in Ruby _ruby topics

Source: Internet
Author: User
Tags rehash

I've been learning about rails, because learning Java is an introductory language. It's a bit of a bad fit. In particular, Ruby's hash. But it's just a matter of thinking it through. It's basically a key-value. There is no big problem with writing in the beginning. This is a log I saw on the Internet.

1. How do I create a hash?

Copy Code code as follows:

x = hash.new
x = {}
x = {: A => 1,: B => 2}

These are the ways to create a hash.
The first is the same as the second, which indicates the creation of an empty hash.
The third represents the hash created, with 2 pairs of keys/values.

2. What are the types of hash keys?

Can be any target, such as:

Copy Code code 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}

There are two points to note:
(1) Any target including array, hash can be key.
(2) When using a character as a key, it is best to use the corresponding symbol. For example, the key "a" can be replaced by: a. This is because each character "a" is a target, and: A is unique,

More memory savings.

3. How do I assign a default value to the hash?

Copy Code code as follows:

IRB (main):003:0> x=hash.new ([])
=> {}
IRB (main):004:0> X[:a]
=> []

Represents the creation of a hash whose default value is an empty array [].
Then access X[:a], although this key is not defined beforehand, there is still a default value.

Note that this method assigns a default value that points to the same target, which changes and affects all default values.

Copy Code code as follows:

IRB (main):005:0> x[:a] << 1
=> [1]
IRB (main):006:0> X[:b]
=> [1]

To make each key correspond to a unique default value, you should create a hash:

Copy Code code as follows:

IRB (main):007:0> y=hash.new do |h,k| H[K] =[] End
=> {}

Let's take another look at:

Copy Code code as follows:

IRB (main):009:0> y[:a] << 1
=> [1]
IRB (main):010:0> Y[:b]
=> []

A change in the value does not affect other default values.

4. How to traverse hash?

Copy Code code 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 each method of the hash.

5. How to traverse the hash key and value?

Copy Code code 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

Using the hash keys and values methods, they return an array.

Of course, you can also use the Each_key and Each_value methods, as the name implies is traversing key and value.

Copy Code code 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 I sort the hash?

Ruby's hash actually can be sort, returning a sort two-dimensional array.

Copy Code code 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]]

Ruby also has the Orderedhash class, which lets you sort the hash elements in the order they are inserted, similar to the ability of an array.

7. How do I add and remove elements from the hash?

Add elements to directly define Key/value:

Copy Code code as follows:

IRB (main):040:0> x[7]=8
=> 8

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


Delete the element, use the Delete method, and the parameter is the key you want to delete:

Copy Code code as follows:

IRB (main):042:0> X.delete (7)
=> 8

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

Of course, you can also use delete_if with conditional delete hash elements. For example, delete all keys greater than 3:

Copy Code code as follows:

IRB (main): 074:0* x.delete_if do |k,v| K>3 End
=> {1=>2, 3=>4}

8. How do I find the hash element?

Use Has_key and has_value to determine if there are corresponding keys and values:

Copy Code code 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

In the case of default values, it cannot be judged directly with the if Hash[:key, for example:

Copy Code code as follows:

IRB (main):055:0> Y=hash.new (9)
=> {}

IRB (main):056:0> Y.has_key? : A
=> false

IRB (main):057:0> puts 1 if Y[:A]
1
=> Nil

Other search methods, as well as find, select, and so on, such as finding all keys greater than 2 elements:

Copy Code code 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, using the Invert method:

Copy Code code 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}

How to convert hash and array?

Hash conversion to an array is simple:

Copy Code code as follows:

IRB (main):020:0> x.to_a
=> [[5, 6], [1, 2], [3, 4]]

Array conversion to hash trouble, write yourself a method To_hash:

Copy Code code 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}

What's the value of the hash loss behavior?

Any time a hash key is modified (remember that the key is a target including an array), the value of the loss behavior occurs.

Copy Code code 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]

The value of the key X is modified above, and the value corresponding to the key is lost.
The solution is rehash. Any time you change the value of a key, you have to rehash it once.

Copy Code code 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.