The basic use method of hash in Ruby _ruby special topic

Source: Internet
Author: User

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:

months = Hash.new

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:

#!/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 an array, so the following example is a valid

[1, "=>"] "January"

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:

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:

#!/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


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.