The basic usage of hash in Ruby, and the usage of Rubyhash

Source: Internet
Author: User

The basic usage of hash in Ruby, and the usage of Rubyhash

A set of hash key-value pairs, such as "employee" => "salary ". It is similar to an array, except that the index is any object type through any key, rather than an integer index.

Traversing a hash key or value in sequence may either look arbitrary and will not insert the value in the sequence. If the hash value of the accessed key does not exist, this method returns nil.
Create a hash:

There are various methods in the array to create hash values. You can create an empty hash using the new class method:

months = Hash.new

You can also use new to create a hash. This is a default value, otherwise it is only nil:

Copy codeThe Code is as follows: months = Hash. new ("month ")

Or

Months = Hash. new "month"

When accessing any hash key, there is a default value. If the key or value does not exist, the default value will be returned for accessing the hash table:

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

This produces the following results:

monthmonth#!/usr/bin/rubyH = Hash["a" => 100, "b" => 200]puts "#{H['a']}"puts "#{H['b']}"

This produces the following results:

100200

If any Ruby object can be used as a key, value, or even an array, the following example is valid.

[1,"jan"] => "January"

Built-in hashing methods:

We need a Hash object instance to call the Hash method. As we can see, the following is a Hash object method to create an instance:

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

This will return a new hash value with a given object fill. Now, using the created object, we can call any available instance method. For example:

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

This produces 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.