Replacing subarrays with []= : Array Elements « Array « Ruby

Replacing subarrays with []=

# To delete, assign an empty array
# To insert, assign to a zero-width slice

p a = ('a'..'e').to_a    # => ['a','b','c','d','e']
p a[0,2] = ['A','B']     # a now holds ['A', 'B', 'c', 'd', 'e']
p a[2...5]=['C','D','E'] # a now holds ['A', 'B', 'C', 'D', 'E']
p a[0,0] = [1,2,3]       # Insert elements at the beginning of a
p a[0..2] = []           # Delete those elements
p a[-1,1] = ['Z']        # Replace last element with another
p a[-1,1] = 'Z'          # For single elements, the array is optional
p a[1,4] = nil           # Ruby 1.9: a now holds ['A',nil]
                         # Ruby 1.8: a now holds ['A']: nil works like []


Related examples in the same category

1.have an array that contains objects from different classes, not all just one type.
2.Accessing Elements
3.use the at method
4.Access the last element in the array
5.With -1, you access the last element in an array by looping back around with a negative number.
6.To change three of the elements to have German rather than English spelling.
7.With start and length parameters
8.Change character case of an element