Does Ruby have a string.startswith("abc") built in method?

Ruby

Ruby Problem Overview


Does Ruby have a some_string.starts_with("abc") method that's built in?

Ruby Solutions


Solution 1 - Ruby

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. On Rails you can use the alias String#starts_with? (note the plural - and note that this method is deprecated). Personally, I'd prefer String#starts_with? over the actual String#start_with?

Solution 2 - Ruby

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

Solution 3 - Ruby

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

Solution 4 - Ruby

You can use String =~ Regex. It returns position of full regex match in string.

irb> ("abc" =~ %r"abc") == 0
=> true
irb> ("aabc" =~ %r"abc") == 0
=> false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlankmanView Question on Stackoverflow
Solution 1 - RubyJörg W MittagView Answer on Stackoverflow
Solution 2 - RubyAlexView Answer on Stackoverflow
Solution 3 - RubyLars HaugsethView Answer on Stackoverflow
Solution 4 - RubyNakilonView Answer on Stackoverflow