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

1 Answer

0 votes
# Removes all non-numeric characters from a string, returning a new string containing only digits.
# 
# @param input_string [String] The source string containing alphanumeric and special characters.
# @return [String] A new string containing only numeric digits (0-9).
# @raise [TypeError] If the input is not a String.
def remove_non_numeric(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 \D (non-digit character class) to replace all non-numeric characters with an empty string.
  # This is equivalent togsub(/[^0-9]/, '') but more concise and idiomatic.
  input_string.gsub(/\D/, '')
end

# --- Example Usage ---
if __FILE__ == $PROGRAM_NAME
  begin
    text = "123XYZ +9982-programming 10000000000001language"
    
    # Process the string
    cleaned_text = remove_non_numeric(text)

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


# run:
# 
# Original: 123XYZ +9982-programming 10000000000001language
# Cleaned:  123998210000000000001
# 

 



answered 1 day ago by avibootz

Related questions

...