Topic: Is there a "starts with" method for a string?

I'm trying to validate a URL referral and need to see if the referring URL starts with a certain value.  Is there anything in Ruby like the C# method "StartsWith()"?

Re: Is there a "starts with" method for a string?

Not that I know of, but you could always use regex.

url = 'ftp://ftp.google.ca/'

if url.match(/^ftp/)
  puts 'Match found.'
end


The ^ symbol in regex means 'begins with'. Good luck!

Re: Is there a "starts with" method for a string?

http://api.rubyonrails.org/classes/Acti … ml#M000441

>> 'abcdefg'.starts_with? 'abc'
=> true
>> 'abcdefg'.starts_with? '123'
=> false

Vincent Woo Ruby on Rails Blog

Re: Is there a "starts with" method for a string?

Outside of Rails, you could do:

class String
  def starts_with?(characters)
      self.match(/^#{characters}/) ? true : false
  end
end

Then, just "whatever".starts_with?('w'), which would return true. That isn't the way Rails does it, but my way vs. the Rails way is .000029 x .000011. Good luck!

Re: Is there a "starts with" method for a string?

Only problem is that way will evaluate regular expression characters. Better to just copy the Rails way if you need it outside of Rails.

def starts_with?(prefix)
  prefix = prefix.to_s
  self[0, prefix.length] == prefix
end

Railscasts - Free Ruby on Rails Screencasts