The array size in Ruby can be changed at any time. The elements in the array only save references to objects.
I. Definition
A = array. New ()
A = array. New (5) Create an array of five nil Elements
A = array. New () Create five arrays whose initial values are 1
A = []
A = [1, 2, "a"]
% W (a B c d AB) is used to create a string array, but cannot process strings with spaces
Same as ["a", "B", "C", "D", "AB"]
In addition, Arrays can be used for parallel assignment.
A = 1
B = 2
Can be replaced by a, B = [1, 2]
Ii. Calculation and common methods
<Append, same as ary. Push (OBJ)
+-& | *
Ary. Size/ary. Length
Ary. Concat (other_array) append an array
Ary. Clear
Ary. Delete (OBJ)
Ary. delete_at (INDEX)
Ary. delete_if {| item | block}: delete a qualified element.
Ary. First/ary. Last
Ary. Compact returns a copy that removes Nil
The element of the ary. Flatten array becomes the basic element.
Ary. Index (OBJ) index of the first element equal to OBJ
Ary. insert (index, OBJ) insert
Ary. Join (separator) merges the array into a string linked with separateor
Ary. POP/ary. Shift Delete last and foremost
Ary. Push (OBJ) appending
Ary. Replace (other_array) with Array
Ary. Reverse reverse
Test:
#!/usr/bin/ruby def printResult(args) print args puts "" endprintResult [1,2]<<3 printResult [1,2]+[4,5] printResult [1,2]-[1] printResult [1,2,3]&[2,3,4] printResult [1,2,3]|[2,3,4] printResult [1]*5 printResult "#{[1,2].size()} #{[1,2].length()}" printResult [1,2].concat([2]) a=[1,2] a.clear() printResult a.length a=[2,3,4] printResult a.delete(3) printResult a printResult a.delete_at(0) printResult a printResult [1,2,3,4].delete_if{|item| item==1} a=[1,2,3,4,nil] printResult a.compact b=a.compact() a[1]=5 printResult b[1] printResult [1,2,[1,2]].flatten() printResult [1,2,3].index(2) printResult [1,3].insert(1,2) printResult [1,2,3].join("@@@") a=[1,2,3] printResult a.pop() printResult a a.shift() printResult a printResult a.push(2) printResult a.replace([nil,2,3]) printResult a.reverse()
Result:
[1, 2, 3]
[1, 2, 4, 5]
[2]
[2, 3]
[1, 2, 3, 4]
[1, 1, 1, 1, 1]
2 2
[1, 2, 2]
0
3
[2, 4]
2
[4]
[2, 3, 4]
[1, 2, 3, 4]
2
[1, 2, 1, 2]
1
[1, 2, 3]
[Email protected] @ [email protected] @ 3
3
[1, 2]
[2]
[2, 2]
[Nil, 2, 3]
[3, 2, nil]
[Finished in 0.1 s]
Iii. Search, modification, and sorting Iteration
Refer to Ruby's enumerable