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"}