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'
#  w  w w . ja v a2  s. co  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  ww. j a v a  2  s. c  o  m

Result

Related Topic