Ruby - String String Indexing

Introduction

Strings and arrays in Ruby are indexed from the first character at index 0.

To replace the character e with u in the string s which contains "Hello world", you would assign a new character to index 1:

Demo

s = "hello world" 
s[1] = 'u'

If you index into a string in order to find a character at a specific location.

  • Ruby 1.8 returns a numeric ASCII code of the character
  • Ruby 1.9 returns the character itself.

Demo

s = "Hello world" 
puts( s[1] )    #=> Ruby 1.8 displays 101; Ruby 1.9 displays 'e'

Result

To obtain the actual character from the numeric value returned by Ruby 1.8, you can use a double index to print a single character, starting at index 1:

s = "Hello world" 
puts( s[1,1] ) # prints out 'e' 

To get the numeric value of the character returned by Ruby 1.9, you can use the ord method like this:

Demo

s = "hello world" 
puts( s[1].ord)

Result

More example

Demo

s = "Hello world" 
puts( s[1] ) #  w  ww.j av a 2  s .  c o m
achar=s[1] 
puts( achar ) 
puts( s[1,1] ) 
puts( achar.ord )

Result

You can use double-indexes to return more than one character.

To return three characters starting at position 1, you would enter this:

Demo

s = "hello world" 
puts( s[1,3] )     # prints 'ell'

Result

you could use the two-dot range notation:

Demo

s = "hello world" 
puts( s[1..3] )     # also prints 'ell'

Result

Related Topic