Ruby - Arrays Indexing Assignment

Introduction

You can make assignments by indexing into an array.

Here, for example, I first create an empty array and then put items into indexes 0, 1, and 3.

The "empty" slot at index 2 will be filled with a nil value:

Demo

arr = []  
arr[0] = [0] #  ww w.j  a v  a  2s  . c om
arr[1] = ["one"] 
arr[3] = ["a", "b", "c"] 
p arr
# arr now contains: 
# [[0], ["one"], nil, ["a", "b", "c"]]

Result

Once again, you can use start-end indexes, ranges, and negative index values:

Demo

arr2 = ['h','e','l','l','o',' ','w','o','r','l','d'] 

arr2[0] = 'H' #   ww  w.  ja  v a  2  s.  co m
arr2[2,2] = 'L', 'L' 
arr2[4..6] = 'O','-','W' 
arr2[-4,4] = 'a','l','d','o' 
p arr2
# arr2 now contains: 
# ["H", "e", "L", "L", "O", "-", "W", "a", "l", "d", "o"]

Result

Related Topic