Ruby has many ways to access substrings and one of the most common ways to do so is by using the bracket notation. These brackets may contain a pair of fixnums, a range, a regular expression, or even a string. In this post we will go over all cases.
Fixnum
If ruby sees that a pair of fixnum values are used, ruby will treat them as an offset and a length. The result is the corresponding substring.
1 2 3 4 5 6 7 8 9 10 11 | string = "Hello World" substr1 = string[6,5] # "World" substr2 = string[6,50] # "World" (You can specify a longer length than the length of the string) substr3 = string[11,-5] # nil (the length can't be negative in this case) # Its important to note that these are offsets and lengths, not beginning and ending offsets so you start at 1 not 0 # Now if you have a negative offset, you would start counting from the end of the string and the length would go forward from there. string = "Hello World" substr1 = string[-6,6] # " World" substr2 = string[-11,5] # "Hello" |
Range
Assuming you know how to specify a range, the range is taken in as a range of indexes into a string. Within substrings, ranges may have negative numbers but the smaller number must always be first in the range or it will return nil.
1 2 3 4 5 | string = "Hi Neighbor" substr1 = string[3..7] # "Neigh" substr1 = string[-5..-1] # "ghbor" substr1 = string[-1..-5] # nil substr1 = string[25..40] # nil |
Regular Expression
When using regular expressions, the string matching the pattern will be returned
1 2 3 4 | string = "Jordans are cool" substr1 = string[/j..n/] # "Jordan" substr1 = string[/s.*c/] # "s are c" substr1 = string[/foo/] # nil |
Strings
When a string is specified, that string will be returned if it appears in the given string object
1 2 3 4 5 | string = "President" substr1 = string["Pres"] # "Pres" substr1 = string["dent"] # "dent" substr1 = string["sid"] # "sid" substr1 = string["foo"] # nil |
Assigning
One other cool thing about Ruby substrings is that you can assign (insert) other strings into a given string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | string = "Hello World" string[6,5] = "Jared" # "Jared" puts string # "Hello Jared" string2 = "Hello World" string2[-6,6] = " Jared" # " Jared" puts string2 # "Hello Jared" string3 = "Howdy Neighbor" string3[6..13] = "Friend" # "Friend" puts string3 # "Howdy Friend" string4 = "Jordans are cool" string4[/e/] = " not" # " not" puts string4 #Jordans ar not cool string5 = "City" string5["y"] = "ies" # "ies" puts string5 # "Cities" |
I hope this helps and you enjoyed! Comment, Tweet, Appreciate!




So let me get this straight.
Wow this is awesome.
Comment by jaredd — April 2, 2009 @ 9:16 am