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 conventionally1).
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:
numto accumulate digits of a number as we parse the string.numbersto store the integers once they’ve been extracted.
Here’s the setup:
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:
For the input "I have 2 apples and 5 oranges", this outputs:
