Reputation: 29074
I am new to ruby and recently started reading the Seven languages in Seven Weeks
and at the page 35, there is practice question on
For the string “Hello, Ruby,” find the index of the word “Ruby.”
How do it in Ruby? Need some guidance ..
Upvotes: 2
Views: 4513
Reputation: 4114
from the docs:
index(regexp [, offset]) → fixnum or nil Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(ee) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
so for your predicament:
ruby-1.9.3-p194@heroku macbook-5:$ irb
s="1.9.3p194 :001 > s="hello, ruby,"
=> "hello, ruby,"
1.9.3p194 :002 > s.index("ruby")
=> 7
Upvotes: 0