OneBite.Dev - Coding blog in a bite size

check if a string contains only letters in Ruby

Code snippet on how to check if a string contains only letters in Ruby

  def consist_of_letters?(str)
    str =~ /^[a-zA-Z]+$/
  end

This code uses a regular expression to check if a string is made up of only letters. The code defines a method called “consist_of_letters?” that takes a string as an argument (str). The regular expression checks that the str begins with a letter [a-zA-Z] (either upper or lower case) and continues with one or more additional letters until the end of the string $. The =~ comparison operator is then used to compare the str content with the regular expression. If matching, the method returns true and if not, it returns false.

ruby