Arrays and Hash tables
Ruby's arrays and hash tables are indexed collections. Both are saved objects collection and can be read by key. The key of the array is a number, but the hash table supports the object as a key. They all grow with the addition of new elements. The array is more efficient in terms of accessing elements, but the hash table is more flexible. Both arrays and hash tables can hold different types of objects; You can use an array to save numbers, strings, and floats, just as you would see when you wait.
You can use the array literal to create and initialize a new array--a collection of elements surrounded by brackets. For an array, you can get each element by using the number between brackets, as the example shows. Note that Ruby's array starts at 0.
A = [1, ' cat ', 3.14] # array with three elements # access the ' a '-
a[0]-> 1
# Set the Thir D element
a[2] = nil
# dump out the array
a-> [1, Cat, nil]
You may have noticed that we used a special value nil in the example. In many languages, the concept of nil (or null) is "no object". In Ruby, this is not the case; Nil is an object, just like any other object; it stands for nothing. Anyway, let's go back to the array and hash table.
Sometimes, creating an array of words is a painful thing, and it contains many quotes and commas. Luckily, Ruby has a quick way:%w can use us only to do what we want to do.
A = [' Ant ', ' bee ', ' cat ', ' dog ', ' elk ']
a[0]-> ' ant ' a[3]-> ' dog ' # This is the
same:
a =%w{ant bee Cat Dog Elk}
a[0]-> "Ant" A[3]-> "
Dog"
Ruby's hash table and array are similar. The hash table uses curly braces instead of brackets. A hash table needs to provide two objects for each item: one is a key and the other is its value.
For example, you want to show music equipment for a band. You can use a hash table to implement it.
Inst_section = {
' cello ' => ' string ',
' clarinet ' => ' woodwind ',
' drum ' => ' percussion ',
' Oboe ' => ' woodwind ', ' trumpet ' => ' brass ', ' violin ' => '
string '
}