From: Stefano Crocco Date: 2007-11-06T22:07:47+09:00 Subject: Re: Start of string? Alle marted́ 6 novembre 2007, Jari Williamsson ha scritto: > What't the most elegant way to find a substring match at the very start > of a string? > > Currently I'm using this approach: > a = "long string" > key = "long" > if a[0, key.length] == key then > > ...while this might look ok, it doesn't look so good with constant strings: > if a[0, 4] == "long" then > or > if a[0, "long".length] == "long" then > > I guess what I'm looking for is something like: > if a.startswith("long") then > > Is there any such solution? > > > Best regards, > > Jari Williamsson You can use a regexp: if a.match /^long/ then ... The ^ at the beginning of the regexp means that the regexp should be matched at the beginning of the string (actually, of the line. If your string is multiline, you need to use \A to match the beginning of the string). If the string you want to look for is stored in a variable, you can use string interpolation inside the regexp: str = "long" if a.match /^#{str}/ then Of course, this can cause problems if str contains characters which are special in a regexp. In this case, you need to quote it: str = "long" if a.match /^#{Regexp.quote(str)}/ then I hope this helps Stefano