Lesson 2
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:

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

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:

Ruby
1input_string.each_char do |char| 2 if char =~ /\d/ # Check if the character is a digit 3 num += char 4 elsif !num.empty? 5 numbers << num.to_i # Add the accumulated number to the list 6 num = "" # Reset for the next number 7 end 8end 9 10# Add any remaining number after the loop 11numbers << num.to_i unless num.empty? 12 13puts numbers.inspect

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

Ruby
1[2, 5]
Step 3: Calculating the Product

Next, we calculate the product of all the numbers in the numbers array. Starting with 1 (the identity value for multiplication), we iterate through the array and multiply each number by the current product.

Ruby
1result = 1 2numbers.each do |number| 3 result *= number 4end 5 6puts result

For the input above, this outputs:

Ruby
110
Complete Method

Now let’s combine all the steps into a single method:

Ruby
1def parse_and_multiply_numbers(input_string) 2 num = "" 3 numbers = [] 4 5 # Extract numbers from the string 6 input_string.each_char do |char| 7 if char =~ /\d/ # Check if the character is a digit 8 num += char 9 elsif !num.empty? 10 numbers << num.to_i 11 num = "" 12 end 13 end 14 numbers << num.to_i unless num.empty? # Add any remaining number 15 16 # Calculate the product of all numbers 17 result = 1 18 numbers.each do |number| 19 result *= number 20 end 21 22 result 23end 24 25# Example usage 26puts parse_and_multiply_numbers("I have 2 apples and 5 oranges") # Outputs: 10

This method effectively extracts numbers from the string, handles cases where there are no numbers, and computes the product.

Lesson Summary

Great job! You’ve just created a method that parses strings to extract numbers and calculates their product. This exercise demonstrates the power of combining Ruby’s string manipulation and iteration tools to solve practical problems.

Want to take it further? Try modifying the method to sum the numbers instead of multiplying them or adapt it to handle floating-point numbers. Experimenting with variations will deepen your understanding and hone your skills. Keep practicing, and happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.