add method(uniq, -, |, &, flatten, compact) and test of Array to mruby-array-ext
[mruby.git] / mrbgems / mruby-array-ext / test / array.rb
blob1c441cec469fab0cab45fdb2b43199683f1a9310
1 ##
2 # Array(Ext) Test
4 assert("Array::try_convert") do
5   Array.try_convert([1]) == [1] and
6   Array.try_convert("1").nil?
7 end
9 assert("Array#assoc") do
10   s1 = [ "colors", "red", "blue", "green" ]
11   s2 = [ "letters", "a", "b", "c" ]
12   s3 = "foo"
13   a  = [ s1, s2, s3 ]
15   a.assoc("letters") == [ "letters", "a", "b", "c" ] and
16   a.assoc("foo").nil?
17 end
19 assert("Array#at") do
20   a = [ "a", "b", "c", "d", "e" ]
21   a.at(0)  == "a" and a.at(-1) == "e"
22 end
24 assert("Array#rassoc") do
25   a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
27   a.rassoc("two") == [2, "two"] and
28   a.rassoc("four").nil?
29 end
31 assert("Array#uniq!") do
32   a = [1, 2, 3, 1]
33   a.uniq!
34   a == [1, 2, 3]
35 end
37 assert("Array#uniq") do
38   a = [1, 2, 3, 1]
39   a.uniq == [1, 2, 3] && a == [1, 2, 3, 1]
40 end
42 assert("Array#-") do
43   a = [1, 2, 3, 1]
44   b = [1]
45   c = 1
46   e1 = nil
48   begin
49     a - c
50   rescue => e1
51   end
53   (a - b) == [2, 3] and e1.class == TypeError and a == [1, 2, 3, 1]
54 end
56 assert("Array#|") do
57   a = [1, 2, 3, 1]
58   b = [1, 4]
59   c = 1
60   e1 = nil
62   begin
63     a | c
64   rescue => e1
65   end
67   (a | b) == [1, 2, 3, 4] and e1.class == TypeError and a == [1, 2, 3, 1]
68 end
70 assert("Array#&") do
71   a = [1, 2, 3, 1]
72   b = [1, 4]
73   c = 1
74   e1 = nil
76   begin
77     a & c
78   rescue => e1
79   end
81   (a & b) == [1] and e1.class == TypeError and a == [1, 2, 3, 1]
82 end
84 assert("Array#flatten") do
85   [1, 2, "3", {4=>5}, :'6'] == [1, 2, "3", {4=>5}, :'6'].flatten and
86   [1, 2, 3, 4, 5, 6] == [1, 2, [3, 4, 5], 6].flatten and
87   [1, 2, 3, 4, 5, 6] == [1, 2, [3, [4, 5], 6]].flatten and
88   [1, [2, [3, [4, [5, [6]]]]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(0) and
89   [1, 2, [3, [4, [5, [6]]]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(1) and
90   [1, 2, 3, [4, [5, [6]]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(2) and
91   [1, 2, 3, 4, [5, [6]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(3) and
92   [1, 2, 3, 4, 5, [6]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(4) and
93   [1, 2, 3, 4, 5, 6] == [1, [2, [3, [4, [5, [6]]]]]].flatten(5)
94 end
96 assert("Array#flatten!") do
97   [1, 2, 3, 4, 5, 6] == [1, 2, [3, [4, 5], 6]].flatten!
98 end
100 assert("Array#compact") do
101   a = [1, nil, "2", nil, :t, false, nil]
102   a.compact == [1, "2", :t, false] && a == [1, nil, "2", nil, :t, false, nil]
105 assert("Array#compact!") do
106   a = [1, nil, "2", nil, :t, false, nil]
107   a.compact!
108   a == [1, "2", :t, false]