How to remove all non-alphanumeric characters from a string in Ruby

1 Answer

0 votes
# Removes all non-alphanumeric characters from a string, returning a new string 
# containing only letters and numbers.
# 
# @param input_string [String] The source string containing punctuation, symbols, and spaces.
# @return [String] A new string containing only alphanumeric characters.
# @raise [TypeError] If the input is not a String.
def remove_non_alphanumeric(input_string)
  # Guard clause: validate input type
  unless input_string.is_a?(String)
    raise TypeError, "Input must be a valid String."
  end

  # Use gsub with the [:alnum:] POSIX character class negated ([^...]) 
  # to replace all non-alphanumeric characters with an empty string.
  input_string.gsub(/[^[:alnum:]]/, '')
end

# --- Example Usage ---
if __FILE__ == $PROGRAM_NAME
  begin
    text = "Hello, World! 123_#$ Ruby-Programming."
    
    # Process the string
    cleaned_text = remove_non_alphanumeric(text)

    # Output results
    puts "Original: #{text}"
    puts "Cleaned:  #{cleaned_text}"
    
  rescue StandardError => e
    warn "Error: #{e.message}"
    exit(1)
  end
end


# run:
#
# Original: Hello, World! 123_#$ Ruby-Programming.
# Cleaned:  HelloWorld123RubyProgramming
#

 



answered 1 day ago by avibootz

Related questions

...