Arrays - Initializing
[ 1 , 2 , 3 ] # => [1, 2, 3] Array.new(2) # => [nil, nil] Array.new(5) { |i| i * 5 } # => [0, 5, 10, 15, 20] Array.new(2) { Array.new(2) } # => [[nil, nil], [nil, nil]] ary = [ ] # => [] ary = Array.new # => [] |
# initializing array of strings on whitespace |
%w(this that, and the other) # => ["this", "that,", "and", "the", "other"] |
Accessing and Assigning
ary = %w(ruby python perl php javascript c) ary[0] # => "ruby" ary[1] # => "python" ary[2] # => "perl" ary[3] # => "php" ary[4] = 'ecmascript' ary # => ["ruby", "python", "perl", "php", "ecmascript", "c"] |
# negative indexes are applied from the end |
ary[-1] # => "c" ary[-2] # => "ecmascript" ary[-3] # => "php" |
# first and last |
ary.first # => "ruby" ary.last # => "c" |
# subarrays give a range, or a start index and length |
ary # => ["ruby", "python", "perl", "php", "ecmascript", "c"] ary[0..2] # => ["ruby", "python", "perl"] ary[-3..-1] # => ["php", "ecmascript", "c"] ary[2, 3] # => ["perl", "php", "ecmascript"] |
# can replace a range of indexes with elements from an array (size doesn't need to match) |
ary # => ["ruby", "python", "perl", "php", "ecmascript","c"] ary[1..2] = [9,8,7,6,5,4,3,2,1] ary # => ["ruby",9 8,7,6,5,4,3,2,1,"php,"ecmascript", "c"] ary = Array(0..10) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ary.insert(5,'five') ary # => [0, 1, 2, 3, 4, "five", 5, 6, 7, 8, 9, 10] |
Sorting
^before = [3,6,3,0,8,235,-3]
after = before.sort
before # => [3, 6, 3, 0, 8, 235, -3]
after # => [-3, 0, 3, 3, 6, 8, 235]^
|
|
|
|
|
|