Ruby Array Use tutorial _ruby topics

Source: Internet
Author: User
Tags hash split
You create an array by listing the elements in square brackets and separating them from each other by commas. The array of Ruby can accommodate different object types

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


Just like the string mentioned earlier. Arrays can also 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 an index 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"]


(The negative index represents the offset to the end of the array, not the beginning.)

Arrays can be converted to and from strings, using join and split respectively:

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


Hash table

An associative array is not accessed through a sequential numeric index. Instead, it is accessed through any type of primary key (key). Such arrays are sometimes called hashes (hash) or dictionaries (dictionary). In Ruby, we tend to use the term hash. Separate pairs of elements by commas Enclose it in braces ({}), which makes up a hash table. You search with a keyword in a hashtable, just as you would use an index to extract the data in an array.

Copy Code code as follows:

ruby> h = {1 => 2,  "2"  =>   "4"} 
   {1=>2,  "2" => "4"} 
ruby> h[1] 
 & nbsp; 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 
R uby> 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.