To check if a string starts with a specific prefix in Ruby, you can use the start_with?
method of the String class.
In this example,
str1
with a value of "Hello World"
.start_with?
method of the string object str1
with the prefix "Hello"
.start_with?
method returns true
if the string starts with the specified prefix; otherwise, it returns false
.str1 = "Hello World"
starts_with_hello = str1.start_with?("Hello")
puts "String starts with prefix 'Hello': #{starts_with_hello}"
String starts with prefix 'Hello': true
In this example,
str2
with a value of "apple"
.start_with?
method of the string object str2
with the prefix "banana"
.start_with?
method returns true
if the string starts with the specified prefix; otherwise, it returns false
.str2 = "apple"
starts_with_banana = str2.start_with?("banana")
puts "String starts with prefix 'banana': #{starts_with_banana}"
String starts with prefix 'banana': false
In this tutorial, we learned How to Check if String starts with Specific Prefix in Ruby language with well detailed examples.