To check if a string contains only alphabets and numbers in Ruby, you can use regular expressions with the match?
method.
In this example,
match?
method of the string object with the regular expression pattern to check if the string matches the pattern.match_alphabets_and_numbers
will be true
, otherwise false
.str = "Hello123"
pattern = /^[a-zA-Z0-9]+$/
match_alphabets_and_numbers = !!(str.match?(pattern))
puts "String contains only alphabets and numbers: #{match_alphabets_and_numbers}"
String contains only alphabets and numbers: true
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in Ruby language with well detailed examples.