Ruby/String/index

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Index and last index a pattern

text = "hello world"
pattern = /l/
first = text.index(pattern)       # 2: first match starts at char 2
n = Regexp.last_match.end(0)      # 3: end position of first match
second = text.index(pattern, n)   # 3: search again from there
last = text.rindex(pattern)       # 9: rindex searches backward from end



line[line.index("k")]

line = "A horse! a horse! my kingdom for a horse!"
line[line.index("k")] # => 107
line[line.index("k")].chr # => "k"



Replace first vowel with an asterisk

s = "hello"       
s[/[aeiou]/] = "*"      # Replace first vowel with an asterisk



The index method returns the index location of a matching substring.

So if you use index like this:
line = "A horse! a horse! my kingdom for a horse!"
puts line.index("k")