Array and hash in Ruby.

Source: Internet
Author: User

Array and hash in Ruby.

The array (arrays) and hash (hashes) of Ruby are indexed collections ).

Both store the collection of objects and access them through keys. The key of the array is an integer. The hash List supports using any object as its key. Array and hash are adjusted as needed to save new elements. Accessing array elements is efficient, but the hash provides flexibility. Any specific array or hash list can save different types of objects.

Use array literal (array literal)-place a group of elements between square brackets-you can create and Initialize New array objects. With an array object, you can access a single element by providing an index between square brackets, as shown in the following example. Note that the index of the Ruby array starts from scratch.

A = [1, 'cat ', 3.14] # arrays with three elements # access the first element a [0]-> 1 # Set the third element a [2] = nil # display this array a-> [1, 'cat', nil]

You may have noticed that the special value nil is used in this example. In many languages, nil (or null) refers to "no object ". In Ruby, this is different. nil is an object, just like other objects, but it is used to indicate objects without anything.

Sometimes it is a pain to create an array of words-many quotation marks and commas must be processed. Fortunately, Ruby has a shortcut: % w can accomplish what we want to do.

a = ['ant','bee','cat','dog','elk']a[0] -> "ant"a[3] -> "dog"#this is the same:a = %w{ant bee cat dog elk}a[0] -> "ant"a[3] -> "dog"

Ruby's hash list is similar to an array. Hash literal uses curly brackets instead of square brackets. This literal must provide two objects for each item: a key and a value ).

For example, if you want to map an instrument to the Symphonic chapter to which it belongs, you can use the scattered list to do this:

inst_section = {'cello'   => 'string','clarinet' => 'woodwind','drum'  => 'percussion','oboe'   => 'woodwind','trumpet' => 'brass','violin'   => 'string'}

=> The key is on the left and the value is on the right ). In a hash table, keys must be unique (there cannot be two "drum" items ). The keys and values in the hash list can be any object-you may have such a hash list, whose values are arrays or other HASH lists.

The hash is indexed using the same square brackets as the array.

inst_section['oboe']           -> "woodwind"inst_section['cello']            -> "string"inst_section['bassoon']         -> nil

As shown in the preceding example, by default, if a hash table is indexed with a key that is not included in the hash table, the hash table returns nil. This is usually convenient. For example, in a conditional expression, nil means false. Sometimes you may want to change the default action. For example, when a hash is used to calculate the number of times each key appears, it is very convenient if the default value is 0. This is easy: You can specify a default value when creating a new empty hash.

histogram = Hash.new(0)histogram['key1']            ->0histogram['key1'] = histogram['key1']+1histogram['key1']            ->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.