From: Golda Bence Date: 2007-11-06T22:08:45+09:00 Subject: Re: Start of string? Hi! Take a look at Regexp class: http://www.ruby-doc.org/core/classes/Regexp.html ...after that your starts_with? method should be similar to this one: class String def starts_with?(a_string) self =~ Regexp.new('^%s' % [ a_string ]) end end a = "long string" a.starts_with?("long") # => 0 a.starts_with?("not soo long") # => nil !note: in ruby 0 (Fixnum) means true in a condition, so does "" (String), but nil (NilClass) means false. Cheers, Bence Jari Williamsson wrote: > 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