Change a string with range : String Range « String « Ruby






Change a string with range


s = "hello"
s[2..3]           # "ll": characters 2 and 3
s[-3..-1]         # "llo": negative indexes work, too
s[0..0]           # "h": this Range includes one character index
s[0...0]          # "": this Range is empty
s[2..1]           # "": this Range is also empty
s[7..10]          # nil: this Range is outside the string bounds
s[-2..-1] = "p!"     # Replacement: s becomes "help!"
s[0...0] = "Please " # Insertion: s becomes "Please help!"
s[6..10] = ""        # Deletion: s becomes "Please!"

 








Related examples in the same category

1.enter a string as the argument to []=, and it will return the new, corrected string, if found; nil otherwise.
2.enter a range to indicate a range of characters you want to change. Include the last character with two dots (..)
3.Get substring from a string object
4.Getting the Parts of a String You Want
5.String range with string.length
6.Generating a Succession of Strings