Ruby array tutorial

Source: Internet
Author: User

You can create an array by listing elements in square brackets and separating them with commas (,). The Ruby array can adapt to different object types.

Ruby> ary = [1, 2, "3"]
[1, 2, "3"]


Just like the string mentioned above, Arrays can be multiplied or added.

Ruby> ary + ["foo", "bar"]
[1, 2, "3", "foo", "bar"]
Ruby> ary * 2
[1, 2, "3", 1, 2, "3"]


We can use indexes to access any part of the array.

Ruby> ary [0]
1
Ruby> ary [0, 2
[1, 2]
Ruby> ary [0 .. 1]
[1, 2]
Ruby> ary [-2]
2
Ruby> ary [-2, 2]
[2, "3"]
Ruby> ary [-2...-1]
[2, "3"]


(Negative index indicates the offset to the end of the array, instead of starting from the beginning .)

Arrays can be converted to strings by using join and split:

Ruby> str = ary. join (":")
"
Ruby> str. split (":")
["1", "2", "3"]


Hash table

An associated array is accessed through any type of primary key instead of consecutive numeric indexes. such arrays are sometimes called hash or dictionary ). in Ruby, we tend to use the term hash. pair elements are separated by commas and enclosed in braces ({}) to form a hash table. you use a keyword to search in the hash table, just as you use indexes in the array to extract data.

Copy codeThe Code is as follows:
Ruby> h = {1 => 2, "2" => "4 "}
{1 => 2, "2" => "4 "}
Ruby> h [1]
2
Ruby> h ["2"]
"4"
Ruby> h [5]
Nil
Ruby> h [5] = 10 # appending value
10
Ruby> h
{5 => 10, 1 => 2, "2" => "4 "}
Ruby> h. delete 1 # deleting value
2
Ruby> h [1]
Nil
Ruby> h
{5 => 10, "2" => "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.