ruby_array基本操作

1.创建新的数组[] (*args)

arr = Array.[](1,2,'a','b',/^A/) #or
arr = Array[1,2,'a','b',/^A/]#or
arr = [1,2,'a','b',/^A/]

2.try_convert(obj)->array or nil

Array.try_convert([1])   #=> [1]
Array.try_convert("1")   #=> nil

if tmp = Array.try_convert(arg)
  # the argument is an array
elsif tmp = String.try_convert(arg)
  # the argument is a string
end

3.ary & other_ary -> new_ary
4.ary + other_ary ->new_ary
5.ary - other_ary ->new_ary
6.ary « obj ->ary
7.ary <=> other_ary -> -1,0,+1 or nil
8.ary == other_ary ->bool
9.ary * int ->new_ary
10.ary * str ->new_str

3. [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
4. [ 1, 2, 3 ] + [ 4, 5 ]    #=> [ 1, 2, 3, 4, 5 ]
5. [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]

6. [ 1, 2 ] << "c" << "d" << [ 3, 4 ]#=>  [ 1, 2, "c", "d", [ 3, 4 ] ]

7. [ "a", "a", "c" ]    <=> [ "a", "b", "c" ]   #=> -1
   [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]            #=> +1

9. [ "a", "c" ]    == [ "a", "c", 7 ]     #=> false
   [ "a", "c", 7 ] == [ "a", "c", 7 ]     #=> true
   [ "a", "c", 7 ] == [ "a", "d", "f" ]   #=> false
10.[ 1, 2, 3 ] * 3    #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
11.[ 1, 2, 3 ] * ","  #=> "1,2,3"

assoc(obj) → new_ary or nil 返回开头为obj的数组

s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a  = [ s1, s2, s3 ]#[["colors", "red", "blue", "green"], ["letters", "a", "b", "c"], "foo"]
a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
a.assoc("foo")      #=> nil

combination(n) { |c| block }

a = [1, 2, 3, 4]
a.combination(1).to_a  #=> [[1],[2],[3],[4]]
a.combination(2).to_a  #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
a.combination(4).to_a  #=> [[1,2,3,4]]
a.combination(0).to_a  #=> [[]] # one combination of length 0
a.combination(5).to_a  #=> []   # no combinations of length 5

compact → new_ary

[ "a", nil, "b", nil, "c", nil ].compact#=> [ "a", "b", "c" ]