Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

People also ask

Can I use string startsWith?

JavaScript String startsWith()The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive.

How do you replace letters in a string in Ruby?

The simplest way to replace a string in Ruby is to use the substring replacement. We can specify the string to replace inside a pair of square brackets and set the replace value: For example: msg = "Programming in Ruby is fun!"


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 _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?


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


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

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

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