Ruby: String Operations

By Xah Lee. Date: . Last updated: .

String Length

Length of the string is .length method.

# ruby

xx="this"
p xx.length == 4

Substring

Substring extraction is done by appending a bracket

string[index, count]

to get just 1 character, use:

string[index]

# ruby

xx = "01234567"

p xx[3] == "3"

p xx[0,2] == "01"

# negative index counts from end. -1 is last char.
p xx[-2,2] == "67"

String Join

Strings can be joined by a plus sign +.

# ruby

p "aa" + "bb" == "aabb"

String Repetition

String can be repeated using *.

# ruby

print "this" * 2 # thisthis

Replacing substring

# ruby

# replacing string

xx = "0123456789"

xx[1]= "a"
p xx == "0a23456789"

# start at index 1, replace 8 chars
xx[1,8]= "what"
p xx == "0what9"

Find substring

# ruby

# get the start index of a substring
p "in love?".index("love") == 3

p "in love?".index("456") == nil
# not found

Split a string into a array

# ruby

p "once upon a time".split(" ") == ["once", "upon", "a", "time"]

Ruby String