Ruby/String/String Range
Материал из Wiki.crossplatform.ru
Версия от 17:10, 26 мая 2010; (Обсуждение)
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!"
enter a range to indicate a range of characters you want to change. Include the last character with two dots (..)
speaker = "This is a test. This is a test. This is a test. This is a test. This is a test. " speaker[13..15]= "This is a test. " # => "the Third" p speaker # => "King Richard the Third"
enter a string as the argument to []=, and it will return the new, corrected string, if found; nil otherwise.
speaker = "this is a test, 2007" speaker[", 2007"]= "III" # => "III" p speaker
Generating a Succession of Strings
("aa".."ag").each { |x| puts x } # aa # ab # ac # ad # ae # af # ag
Get substring from a string object
string = "My first string" # => "My first string" string[3, 5] # => "first"
Getting the Parts of a String You Want
s = "My kingdom for a string!" s.slice(3,7) # => "kingdom" s[3,7] # => "kingdom" s[0,3] # => "My " s[11, 5] # => "for a" s[11, 17] # => "for a string!"
String range with string.length
s = "My kingdom for a string!" s[15...s.length] # => "a string!"