Today we're learning about arrays and hashes, and arrays are often used in many programming languages.
Array:
An array is a container for storing data, and in Ruby, the data stored in an array can be any type of data; This differs from Java, in Java, where arrays are structures that store the same type of data.
1. How do you define an array in Ruby?
Use [] to frame the elements, while the "," interval is used between elements. As follows
name = ["Windy", "Cindy", "Amee", "Tom"]
name = [] #声明了一个空数组, undefined array
name = [1, "Song", 3, "Xiao Lin"]
2. How do I get an array element?
In Ruby, the array element is obtained from the array name [index], which is the same as Java. And the index number is starting from 0. For example, in the above example, if you want to remove the "windy" element, you use Name[0], and P name[3] #-> "Tom."
3. How do I put an object in an array?
You can assign values directly to an array element
name = ["Alice", "John", "Bob", "Jessie"]
NAME[1] = "Jack"
P name #-> ["Alice", "Jack", "Bob", "Jessie"]
NAME[4] = "Windy"
P name #-> ["Alice", "Jack", "Bob", "Jessie", "Windy"]
4. How do I get the size of the array?
Use the size method to return the size of an array. For example, the first time the array name defined in the above instance, p name.size #-> 4 in Java, the array has attribute length to get the size of the array.
5. How do I deal with the contents of an array?
You can use each of the arrays to handle the contents of an array in pairs, the syntax is as follows:
=begin
Grammar:
Array. Each {| variable |
The action to perform
}
=end
name = [2, 5,, 6, 9]
name.each{|number|
Prints number+1, "\ n"
}
#-> 3
# 6
# 7
# 10
This is similar to the For Each loop in Java.
HASH:
Hash is one of the most frequently used containers, and in Ruby it can store objects using data such as strings, similar to the map container in Java.
1. How do I define a hash?
Use {} To box the hash object, and each element appears as a key=>value, and the elements pass between the "," interval.
Name_list = {"=>" "Windy", "=>" Cindy "," "=>" Terry "}
2. How do I get the elements in the hash?
Use the hash name [key value] to get the hash element, for example,
P name_list["A"] #-> "Windy"
3. How do I store objects in a hash?
Similar to the array above, assign values directly to the hash element, for example: name_list["+" = "Amy"
Because the hash is not in a fixed order, the data cannot be retrieved in the order in which it was stored, which is similar to the hash table in Java.
4. How to deal with hash content by item
Like an array, it also processes its elements by its each method
=begin
Grammar
Hash.each {|key variable, value variable |
The action you want to perform
}
=end
name_list.each{|key, value|
Print key, "=", value, "\ n"
}
# "->" = "Windy"
# "A" = "Cindy"
# "+" = "Terry"
Ruby also has a redirect (redirect) function, which is to store the execution result file in another file, using the "> filename", for example, Ruby name_list.rb > Name_list.txt