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.
CopyCode The 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 "}