H
hongseok.yoon
See bellow code please.
1 obj1 = "object1"
2 obj2 = "object2"
3 obj3 = "object3"
4
5 arr1 = Array.new
6 arr2 = Array.new
7
8 arr1 << obj1
9 arr1 << obj2
10
11 arr2 << obj3
12
13 puts "<arr1>"
14 arr1.each {
15 | element |
16 puts element
17 }
18
19 puts "<arr2>"
20 arr2.each {
21 | element |
22 puts element
23 }
24
25 arr1.push( arr2 )
26 puts "<arr1 << arr2>"
27 arr1.each {
28 | element |
29 puts element
30 }
31
32 arr2.clear
33 puts "<arr2.clear>"
34
35 puts "<arr2>"
36 arr2.each {
37 | element |
38 puts element
39 }
40
41 puts "<arr1>"
42 arr1.each {
43 | element |
44 puts element
45 }
result is...
<arr1>
object1
object2
<arr2>
object3
<arr1 << arr2>
object1
object2
object3
<arr2.clear>
<arr2>
<arr1>
object1
object2
In the last list of arr1, there's no object3. Why? Does Array#push()
method append the array as a refrence? If so, why it does? And after
arr2 had been cleared, I still can access to 3rd member of arr1 without
exceptions or errors.
Yes, I can use clone() method for Array#push. But before, I hope to
know the reason why RUBY's Array#push method works like above.
Thanks.
1 obj1 = "object1"
2 obj2 = "object2"
3 obj3 = "object3"
4
5 arr1 = Array.new
6 arr2 = Array.new
7
8 arr1 << obj1
9 arr1 << obj2
10
11 arr2 << obj3
12
13 puts "<arr1>"
14 arr1.each {
15 | element |
16 puts element
17 }
18
19 puts "<arr2>"
20 arr2.each {
21 | element |
22 puts element
23 }
24
25 arr1.push( arr2 )
26 puts "<arr1 << arr2>"
27 arr1.each {
28 | element |
29 puts element
30 }
31
32 arr2.clear
33 puts "<arr2.clear>"
34
35 puts "<arr2>"
36 arr2.each {
37 | element |
38 puts element
39 }
40
41 puts "<arr1>"
42 arr1.each {
43 | element |
44 puts element
45 }
result is...
<arr1>
object1
object2
<arr2>
object3
<arr1 << arr2>
object1
object2
object3
<arr2.clear>
<arr2>
<arr1>
object1
object2
In the last list of arr1, there's no object3. Why? Does Array#push()
method append the array as a refrence? If so, why it does? And after
arr2 had been cleared, I still can access to 3rd member of arr1 without
exceptions or errors.
Yes, I can use clone() method for Array#push. But before, I hope to
know the reason why RUBY's Array#push method works like above.
Thanks.