内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
例如str = 'abcdefg'
。如何找到这个字符串中的索引?
index(substring [, offset]) → fixnum or nil
index(regexp [, offset]) → fixnum or nil
返回str中给定子字符串或模式(regexp)的第一个匹配项的索引。如果没有找到,则返回nil。如果第二个参数存在,它指定字符串中开始搜索的位置。
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
查看ruby文档以获取更多信息。