Ruby - String indexed using negative values

Introduction

Strings can be indexed using negative values.

-1 is the index of the last character, and you can specify the number of characters to be returned:

Demo

s = "hello world" 
puts( s[-1,1] )     # prints 'd' 
puts( s[-5,5] )     # prints 'world'
# from   w  w  w .  j  a  va2s  .c o m

Result

When specifying ranges using a negative index, you must use negative values for both the start and end indexes:

Demo

s = "hello world" 
puts( s[-5..5] )         # this prints an empty string! 
puts( s[-5..-1] )        # prints 'world'
# from  w w w . j a  v a  2s  .  c  o  m

Result

Related Topic