Ruby - Array Array Indexing

Introduction

You can index from the end of an array using negative numbers, where -1 is the index of the last element, -2 is the second-to-last, and so on.

You can also use ranges, like this:

Demo

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

print( arr[0,5] )    #=> hello (or) ["h", "e", "l", "l", "o"]  
print( arr[-5,5 ] )  #=> world (or) ["w", "o", "r", "l", "d"] 
print( arr[0..4] )   #=> hello (or) ["h", "e", "l", "l", "o"] 
print( arr[-5..-1] ) #=> world (or) ["w", "o", "r", "l", "d"]
#  w  ww  .j  a  va2s  . c o  m

Result

If you use p instead of print to inspect the array, both Ruby 1.8 and 1.9 display the same result:

Demo

arr = ['h','e','l','l','o',' ','w','o','r','l','d'] 
p( arr[0,5] )     #=> ["h", "e", "l", "l", "o"] 
p( arr[0..4] )    #=> ["h", "e", "l", "l", "o"]
# from  w  w  w  .ja v a  2  s.c  om

Result

When you provide two integers in order to return a number of contiguous items from an array, the first integer is the start index, while the second is a count of the number of items ( not an index):

Demo

arr = ['h','e','l','l','o',' ','w','o','r','l','d'] 
p arr[0,5]    # returns 5 chars - ["h", "e", "l", "l", "o"]

Result

Related Topics