How to extract all digits from a string in Ruby

1 Answer

0 votes
#
# extract_digits
# --------------
# Walks through the input string and collects only characters
# that are recognized as digits. Ruby's regular expressions
# provide a concise and efficient way to filter characters.
#
# Using `scan(/\d/)` returns an array of all digit matches,
# and `join` builds the final string.
#
def extract_digits(str)
  # Scan for digit characters and join them into a single string
  str.scan(/\d/).join
end

#
# Main execution
#
str = '5 ruby8go 9001 c c++ 17python'

# Extract digits
digits = extract_digits(str)

# Display results
puts "Original: #{str}"
puts "Digits:   #{digits}"



#
# run:
#
# Original: 5 ruby8go 9001 c c++ 17python
# Digits:   58900117
#

 



answered Sep 17 by avibootz
...