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

Using Strings

By

Using the index operator is ideal when you know the location of the portion of the string you want to change. However, it's rare that you'll know the location, so doing this can be considered a bad practice. Strings may be user-supplied, so there's no guarantee they'll follow a specific format. Also, later changes in the string may change the length of the string, breaking all substring accesses that use the range operator. So, if you have a string "the test" and use the range operator to assign s[6..7] , if you later change the string to "my test" s[6..7] will no longer be valid.

There are two primary String methods that can be used to avoid this pitfall. The split method will split a string into an array of strings. This works best if the String is a collection of records with a clearly defined record seperator, such as a list of names separated by commas. After alterations have been made to the Array returned by split, the join method can be used to join the Array back into a single String.

#!/usr/bin/env ruby

names = "Alice,Bob,Eve"
names_a = names.split(/,/)

names_a.push("Carol", "Dave")
names = names_a.join(',')

puts names
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Split and Join - Using Strings in Ruby

©2014 About.com. All rights reserved.