Tutorial on creating and using hash in Ruby and ruby hash

Source: Internet
Author: User

Tutorial on creating and using hash in Ruby and ruby hash

Hash is a set of key-value pairs similar to "employee" => "salary. Hash indexes are completed by any key of any object type, rather than an integer index. Others are similar to arrays.

The hash traversal order by key or value seems random, and is generally not in the insertion order. If you try to access the hash using a key that does not exist, the method returns nil.
Create a hash

Like arrays, there are different ways to create a hash. You can create an empty hash using the new class method:

months = Hash.new

You can also use new to create a hash with the default value. The hash without the default value is nil:

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

When you access any key in the hash with the default value, if the key or value does not exist, the default value is returned for accessing the hash:

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

This produces the following results:

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

This produces the following results:

100200

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

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

Hash built-in method

We need an instance of the Hash object to call the Hash method. The following describes how to create a Hash object instance:

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

This will return a new hash filled with the given object. 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.keys puts "#{keys}"

This produces the following results:

2, 1

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

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.