enclosed with [ ]
can contain elements with different classes
add element to array:
use <<
ex:
a=[]
a <<>
array adding
ex:
[“test1”] + [“test2”]
--> [ “test1”, “test2” ]
use concat:
ex:
[1,2].concat([3,4])
--> [1,2,3,4]
concat modifies original array
<<:
add element to array
ex:
a=[1,2]
a<<3
---> [1,2,3]
new:
ex:
Array.new(3, "a")
create a three element array ,with each initialized to "a"
a=0
Array.new(3) { a=a+1 }
create a three element array , [1,2,3]
get more than one elements
ex:
a=[1,2,3,4,5]
a[3,2]
---> [4,5]
sort_by
accept block argument
ex:
sort_by{ rand }
sort randomly
join:
[“a”, “b”, “c”].join(‘2’)
--> “a2b2c”
push:
add an element to the end of the array
pop:
remove last element
include:
ex:
[1, 2, 3].include?(1)
---> true
uniq:
ex:
["ab", "c","ab"].uniq
--->["ab", "c"]
multiplication:
ex:
[1,2]*2
--> [1,2, 1,2]
detect:
find the first element that match condition in the array
ex:
[1 , 2, 3].detect { | i | i>2 }
--> 3
find:
find first element that matches
find_all:
find all elements that match condition in the array
ex:
[1,2,3].find_all{ |i| i>1 }
--> [2, 3]
array intersection:
use &
ex:
[1,2,3] & [2,3]
--> [2,3]
%w[a b]
--> ["a", "b"]
sort:
ex:
c=[ [1, 2], [3, 1] ]
c.sort{ |a, b| a[0]<=>b[0] }
--> [ [1,2], [3, 1] ]
c.sort{ |a, b| b[0]<=>a[0] }
--> [[3, 1], [1, 2]]
c.sort{ |a, b| a[1]<=>b[1] }
--> [[3, 1], [1, 2]]
a[0] <=> b[0] compare first element of nested array in ascending order
a[1] <=> b[1] compare second element of nested array in ascending order
b[0] <=> b[1] compare first element of nested array in descending order
unshift:
add an element to the beginning of the array
shift:
remove the first element
zip:
ex:
[1,2].zip([3,4])
--> [ [1,3], [2,4] ]
flatten:
ex:
[1,2, [3,4] ].flatten
--> [1,2,3,4]
reject:
ex:
[1,2,3].reject { |item| item>2 }
---> [1,2]
replace, reverse:
each, each_with_index
include?, empty?, any?, all?
ex:
[1,2,3].any?{ | k| k>2 }
---> true
index:
return the first element equals to parameter
ex:
["a", "b", "c"].index( "b")
---> 1
index with integer <0
count from right
ex:
a= [1, 2, 3]
a[-1]
---> 3
compact:
remove nil element from the array
沒有留言:
張貼留言