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:
s = "hello world" s[1] = 'u'
If you index into a string in order to find a character at a specific location.
s = "Hello world" puts( s[1] ) #=> Ruby 1.8 displays 101; Ruby 1.9 displays 'e'
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:
s = "hello world"
puts( s[1].ord)
More example
s = "Hello world" puts( s[1] ) # from w w w.ja va 2 s . c om achar=s[1] puts( achar ) puts( s[1,1] ) puts( achar.ord )
You can use double-indexes to return more than one character.
To return three characters starting at position 1, you would enter this:
s = "hello world" puts( s[1,3] ) # prints 'ell'
you could use the two-dot range notation:
s = "hello world" puts( s[1..3] ) # also prints 'ell'