From: dblack@... Date: 2006-07-06T02:50:11+09:00 Subject: Re: Find Position of text Hi -- On Thu, 6 Jul 2006, j3n7il jones wrote: > Im trying to recreate a function I had in Delphi for ruby, but cannot > figure out how to search for a string withn a string > > Here is the Delphi code > > function ReplaceString(str, value, replacer: String): String; > var > aPos: Integer; > rslt: String; > begin > aPos := Pos(value, str); > rslt := ''; > result := str;//in case there is nothing to replace, return orig > string > while (aPos <> 0) do begin > rslt := Copy(str, 1, aPos - 1) + replacer; > rslt := rslt + Copy(str, aPos + Length(value), Length(str)); > str := rslt; > aPos := Pos(value, str); > result := rslt; > end; > end; > > As you can see after begin, it calls a pascal function called "pos" > > which just looks for value(a string) within str (another string) and > returns a number, the position of value within str. > > Possible in ruby? Of course -- and there's even a built-in method that does it :-) Actually a couple of them. Check out String#index and String#rindex. str = "This is a string." str.index("is") # 2 str.rindex("is") # 5 (i.e., last occurence) str.index(/i./) # 2 (using regex) The =~ method/operator also returns an index. David -- "To fully realize the potential of Rails, it's crucial that you take the time to fully understand Ruby--and with "Ruby for Rails" David has provided just what you need to help you achieve that goal." -- DAVID HEINEMEIER HANSSON, in the foreword to RUBY FOR RAILS. Complete foreword & sample chapters at http://www.manning.com/black!