Parsing and Multiplying Numbers in Strings

Introduction

Welcome! Today, we’ll explore an exciting and practical challenge that combines string parsing with numerical operations in Ruby. In this lesson, we’ll develop a method to extract numbers from a mixed string and calculate their product.

This task is a great opportunity to practice Ruby’s string manipulation capabilities and strengthen your problem-solving skills. Let’s dive in!

Task Statement and Description

Your goal is to create a Ruby method called parse_and_multiply_numbers. This method takes a string as input, identifies all the numbers embedded within it, converts those numbers into integers, and calculates their product.

Here are some key points to keep in mind:

  • The input string may contain a mix of words, spaces, and numbers.
  • Numbers in the string are separated by non-numeric characters (e.g., spaces or letters).
  • If there are no numbers in the string, the method should return 1 (since the product of an empty set is conventionally 1).

Example: If the input string is "I have 2 apples and 5 oranges", the method should extract 2 and 5, calculate their product, and return 10.

Ready to build this step by step? Let’s go!

Step 1: Initializing Variables

First, we set up variables to collect digits and store numbers. We’ll use:

  • num to accumulate digits of a number as we parse the string.
  • numbers to store the integers once they’ve been extracted.

Here’s the setup:

input_string = "I have 2 apples and 5 oranges"
num = ""
numbers = []

This initializes an empty string num for collecting digits and an empty array numbers to store the extracted integers.

Step 2: Extracting Numbers from the String

We need to process the string character by character to identify and extract numbers. We can iterate through the string using each_char. If a character is a digit, we append it to num. If it’s not a digit and num isn’t empty, we’ve reached the end of a number. At this point, we convert num to an integer, add it to numbers, and reset num.

Here’s the code:

input_string.each_char do |char|
  if char =~ /\d/  # Check if the character is a digit
    num += char
  elsif !num.empty?
    numbers << num.to_i  # Add the accumulated number to the list
    num = ""  # Reset for the next number
  end
end

# Add any remaining number after the loop
numbers << num.to_i unless num.empty?

puts numbers.inspect

For the input "I have 2 apples and 5 oranges", this outputs:

[2, 5]
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal