Mega Code Archive

 
Categories / Ruby / Array
 

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 []