1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

New in 1.9.1: The String Index Operator

What Does the String Index Operator Do in Ruby 1.9.1?

By

In Ruby 1.8, the string index operator, when passed a single integer, returned the ASCII value of the character at that location. For example, "test"[0] would return 116, the ASCII value of the character t.

This behavior has changed in Ruby 1.9 to become more consistent with the behavior of the other variants of the index operator. For example, "test"[0,2] returns the string "te", the first two characters of "test". Why should the the single integer variant behave differently?

This has been changed in Ruby 1.9. The statement "test"[0] will return the single character string "t".

 #!/usr/bin/env ruby
 
 # In Ruby 1.8, this will return 116
 # In Ruby 1.9, this will return "t"
 puts "test"[0]
 
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. New in Ruby 1.9.x
  6. The String Index Operator in Ruby 1.9.1

©2014 About.com. All rights reserved.