How to remove all letters from an alphanumeric string in Ruby

3 Answers

0 votes
# Removes all alphabetic characters (letters) from a given string,
# leaving numbers, symbols, and whitespace intact.
#
# @param input_string [String] The alphanumeric string to process.
# @return [String] The string with all letters removed.
def remove_letters(input_string)
  # Ensure the input is a valid string to prevent runtime errors
  return "" unless input_string.is_a?(String)

  # [[:alpha:]] matches any uppercase or lowercase letter.
  # gsub replaces all matches with an empty string ('').
  input_string.gsub(/[[:alpha:]]/, '')
end

# --- Examples ---
mixed_string = "abc123XYZ456programming789"
p remove_letters(mixed_string) 



# run:
#
# "123456789"
#

 



answered 1 day ago by avibootz
0 votes
def remove_letters_ascii(str)
  str.delete("a-zA-Z")
end

# --- Examples ---
mixed_string = "abc123XYZ456programming789"
p remove_letters_ascii(mixed_string) 


# run:
#
# "123456789"
#

 



answered 1 day ago by avibootz
0 votes
def remove_letters_unicode(str)
  str.gsub(/\p{L}/, '')
end

# --- Examples ---
mixed_string = "abc123XYZ456programming789"
p remove_letters_unicode(mixed_string) 


# run:
#
# "123456789"
#

 



answered 1 day ago by avibootz
...