# Basic syntax again def showArr(msg, b) puts "#{msg}: " unless msg == nil puts b.join(', ') if b end a = [1, 2, 3, 4, 5] showArr('Original array', a) print "\n" #reverse indexing puts "First is #{a[0]}; last is #{a[-1]}" # slice b = a[2, 3] # 3 elements starting from 2 [3, 4, 5] showArr('Slice', b) # range slice b = a[1..3] # From 1 to 3 [2, 3, 4] showArr('Range slice', b) # End range slice b = a[-3..-1] # From -3 to -1 (same as 2 to 4) [3, 4, 5] showArr('End slice', b) # Straight assign b = a b[2] = "dog" # Replace element 2 [1, 2, "dog", 4, 5] showArr('Element assign', b) # Zero fill b[6] = "mouse" # Add element 6, and nil element 5 [1, 2, "dog", 4, 5, nil, "mouse"] showArr('Zero fill', b) # Replace ranges b[2, 3] = [5, 4, 3] # Replace 3 elements starting at 2 [1, 2, 5, 4, 3, nil, "mouse"] showArr('Replaced range', b) # Which can resize the array b[0, 2] = "cat" # Replace 2 elements starting at 0 with a single "cat" ["cat", 5, 4, 3, nil, "mouse"] showArr('Rep Range Resize', b) # It can be used to insert stuff too b[2, 0] = [24, 48, "hut"]# Insert 3 elements at position 2 ["cat", 5, 24, 48, "hut", 4, 3, nil, "mouse"] showArr('Insert elements', b) # Range replace b[1..4] = [11, 12, 13, 14]# Replace elements 1..4 ["cat", 11, 12, 13, 14, 4, 3, nil, "mouse"] showArr('Replace range', b) # Range replace (diff size) b[1..4] = [1, 2] # Replace elements 1..4 with just two ["cat", 1, 2, 4, 3, nil, "mouse"] showArr('Resize range', b) # Range remove b[5..6] = [] # Replace elements 5 and 6 with nothing ["cat", 1, 2, 4, 3 ] showArr('Remove range', b) # End replace b[-2, 2] = [3, 4] # Replace elements 3 and 4 (swap 'em) ["cat", 1, 2, 3, 4] showArr('Replace at end', b) # Range from end b[-5..-4] = [0, 1] # Replace elements 0 and 1 [0, 1, 2, 3, 4] showArr('Range from end', b) showArr("\nFinal array", b) showArr("'a' is changed also (ref assign)", a) # Perl-style iteration while (c = a.shift) puts c end # Flatten arrays muldim = [[1, 2, 3], 4, [[5, 6], 7], 8, 9] showArr('Original',muldim) flat = muldim.flatten showArr('New flattened',flat) # Alternatively, flatten in place muldim.flatten! showArr('Flattened in place',muldim)