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