1. Computing

Using Strings

By

String manipulation calls for the ability to read or change parts of a String variable, not all of it. Ruby accomplishes this with the String's index operator and a number of methods including split, join and gsub.

If the String's index operator is given a Range argument, the characters of the string that are within that range are returned. The index operator can be used to read portions of a string, but it can also be used to change them. If a String is assigned to the value returned by the index operator, the assigned string will be inserted into the original string. If the assigned string is longer than the Range, the original string will be expanded.

#!/usr/bin/env ruby

s = "test"
puts s[0..1] # "te"
puts s[2..3] # "st"
puts s[1..3] # "est"

s[2..3] = "mp" # s = "temp"
s[0..1] = "bu" # s = "bump"
s[0..1] = "shri" # s = "shrimp"
puts s
  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Substrings

©2014 About.com. All rights reserved.