Skip to main content

Ruby: String Methods

Calling a String's method involved first identifying the string either by strig literal or identifier, following the identity with a period symbol (.), and following the symbol with the method identifier. Like programmer defined methods, a return value may be captured or utilized by the invoking script.

The following methods are available on all Strings.

String[]

Like Array, the String class also provides the ability to access a value found at a given index of an array using the square bracket, [], notation. In Ruby, Strings are zero indexed, meaning the first character is found at index 0.

STRING[]
first_number = '555-555-9281'[0]
puts first_number
OUTPUT
5

String.slice

String.slice takes one or two parameters and returns a string of characters. If two parameters are given, they should both be integers. The string returned is the set of characters starting at the index given by the first number, and continuing toward the end of the string until a string of length specified by the second parameter is collected. If one parameter is given and it is a Range, the characters at indices specified by the span of numbers represented by the Range is returned.

STRING.SLICE
phone = '555-555-9281'
puts phone.slice(0, 3)
puts phone.slice(0..3)
OUTPUT
555
555-

String.length

String.length returns the number of characters in the string on which it is invoked.

STRING.LENGTH
length = '555-555-9281'.length
puts length
OUTPUT
12

String.downcase

String.downcase returns the identified string with each character converted to its lowercase corollary.

STRING.DOWNCASE
puts '555-555-9281'.downcase
puts 'Alexa D. Anderson'.downcase
OUTPUT
555-555-9281
alexa d. anderson

String.upcase

String.upcase returns the identified string with each character converted to its capital corollary.

STRING.UPCASE
puts 'Alexa D. Anderson'.upcase
OUTPUT
ALEXA D. ANDERSON