How to extract all floating-point numbers from a string of words in Ruby

1 Answer

0 votes
# Pre-compiled regular expression pattern matching numbers containing an explicit decimal point.
# \b establishes word boundaries; \d+\.\d+ ensures digits precede and follow the dot.
FLOAT_PATTERN = /\b\d+\.\d+\b/

# Extracts all floating-point numbers containing an explicit decimal point from a given text.
#
# @param text [String] Source string containing mixed text and numbers.
# @return [Array<Float>] An array of extracted floating-point values.
def extract_floats(text)
  return [] if text.nil? || text.strip.empty?

  # scan finds all matches matching the pattern in a single pass.
  # map converts each matched substring directly into a Float object.
  text.scan(FLOAT_PATTERN).map(&:to_f)
end

# Main program execution block
def main
  s = 'c/c++ c# go 893725.1045 java python 3.14 php 0.0076 javascript'

  extracted_numbers = extract_floats(s)

  puts 'Extracted floating-point numbers:'
  extracted_numbers.each do |number|
    puts number
  end
end

main



# run:
# 
# Extracted floating-point numbers:
# 893725.1045
# 3.14
# 0.0076
#

 



answered Sep 18 by avibootz

Related questions

...