To check if a string contains only alphabets in Ruby, you can use regular expressions or iterate through each character and check if it is an alphabet using functions like String#each_char
.
In this example,
String#match?
method to check if the string matches the pattern.contains_only_alphabets
to true
, otherwise false
.str = "Hello123"
contains_only_alphabets = !str.match?(/[^A-Za-z]/)
puts "String contains only alphabets: #{contains_only_alphabets}"
String contains only alphabets: false
In this example,
str
with a value of "Hello123"
.String#each_char
method.contains_only_alphabets
to false
and break the loop.str = "Hello123"
contains_only_alphabets = true
str.each_char do |c|
if !c.match?(/[A-Za-z]/)
contains_only_alphabets = false
break
end
end
puts "String contains only alphabets: #{contains_only_alphabets}"
String contains only alphabets: false
In this tutorial, we learned How to Check if String contains only Alphabets in Ruby language with well detailed examples.