The start_with?()
method is used to check if a particular string starts with a specified prefix. The prefix can either be a string or a regular expression.
The start_with?()
method takes more than one parameter. It returns True
if the string starts with at least one of the specified prefixes.
str.start_with?([prefix]+)
str
: This is the string that we check to see if it begins with a particular prefix.
prefix
: This is the prefix that we check for to see if the string str
begins with it.
This method returns a Boolean value. If the string str
starts with the specified prefix or one of the specified prefixes, then the method returns True
. Otherwise, it returns False
.
# create some stringsstr1 = "Edpresso"str2 = "is very"str3 = "great!"str4 = "and awesome!"# check prefixesa = str1.start_with?("Edp") # trueb = str2.start_with?("ver") # falsec = str3.start_with?("gr") # trued = str4.start_with?("awe", "an") # true# print resultsputs a # trueputs b # falseputs c # trueputs d # true
Lines 2–5: We create several string variables and initialize them with values.
Lines 8–10: We check if the strings we created begin with the prefixes that were passed to the start_with?()
method.
Line 11: We pass two prefixes to the start_with?()
method to see if str4
starts with any of them.
Lines 14–17: We print the results to the console.
The method returns False
only in line 9, when we run the code. This is because str2
does not start with "ver"
.
In line 11, d
returns True
because str4
starts with one of the specified prefixes.