presidents= %w[ John Richard Gerald Ronald George
William]; 在其它编程语言中,"数组"一词经常意味着一组相同性质的对象的集合。但在Ruby中,不是这样。在Ruby中,一个"数组"可以是由不同性质的对象参考组成的集合。因此,下面是有效的数组表达形式:
irb(main):001:0> test_array=["zero", "one", "two", "three",
"four"] => ["zero", "one", "two", "three", "four"] irb(main):002:0>
#starting at the second element, replace the next two elements with a
single element irb(main):003:0* test_array[1,2]=1 =>
1 irb(main):004:0> test_array => ["zero", 1, "three",
"four"] irb(main):005:0> #insert a new element after the second
one (zero as a second parameter indicates "insert") irb(main):006:0*
test_array[2,0]=2 => 2 irb(main):007:0> test_array => ["zero", 1,
2, "three", "four"] irb(main):008:0> #add an array of elements after
element 5 irb(main):009:0* test_array[5,0]=[5,6,7] => [5, 6,
7] irb(main):010:0> test_array => ["zero", 1, 2, "three", "four", 5,
6, 7] irb(main):011:0> #replace elements in the index range of 3..4
with the array assigned irb(main):012:0* test_array[3..4]=[3,4] =>
[3, 4] irb(main):013:0> test_array => ["zero", 1, 2, 3, 4, 5, 6,
7] 最后,也许Ruby数组中最有力量的运算可以从数学操作符中找到答案-它们能够从现在数组创建新的数组。例如,+操作符允许你由两个数组的连接创建一个新数组,而*操作符允许你复制或连接一个数组自身若干次。