What is the start_with?() method in Ruby?

Overview

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.

Syntax

str.start_with?([prefix]+)

Parameters

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.

Return value

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.

Code example

# create some strings
str1 = "Edpresso"
str2 = "is very"
str3 = "great!"
str4 = "and awesome!"
# check prefixes
a = str1.start_with?("Edp") # true
b = str2.start_with?("ver") # false
c = str3.start_with?("gr") # true
d = str4.start_with?("awe", "an") # true
# print results
puts a # true
puts b # false
puts c # true
puts d # true

Code explanation

  • 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.

Free Resources