Ruby Coding Practice: Parsing a String with Multiple Matches

Summary

Build a program that utilizes regular expressions to extract a specific set of integers from a string in Ruby.

Exercise File

Code File

Exercise Description

Given the following strings:

Web IconHTML & CSS100%
Command LineLearn the Command Line100%
Ruby IconRuby - Ruby IconRuby50%
Rails IconLearn Ruby on Rails100%
Git IconLearn Git100%
SassLearn Sass20%
JQuery IconjQuery1%
Angular JSLearn AngularJS 1.X100%
Javascript IconLearn JavaScript55%

Write a program that iterates over the strings and outputs the final integer value, storing it in an array.

Input

[
  "Web IconHTML & CSS100%",
  "Command LineLearn the Command Line100%",
  "Ruby IconRuby50%",
  "Rails IconLearn Ruby on Rails100%",
  "Git IconLearn Git100%",
  "SassLearn Sass20%",
  "JQuery IconjQuery1%",
  "Angular JSLearn AngularJS 1.X100%",
  "Javascript IconLearn JavaScript55%"
]

Output

[100, 100, 50, 100, 100, 20, 1, 100, 55]

Real World Usage

I encountered this very problem when I was building a scraper gem that extracted student progress reports from websites and I had to access the values in order to clean up the data.

This type of problem is also important in the world of data science where you will encounter data that needs to be cleaned prior to utilizing it in a machine learning algorithm.

Solution

string_array = [
  "Web IconHTML & CSS100%",
  "Command LineLearn the Command Line100%",
  "Ruby IconRuby50%",
  "Rails IconLearn Ruby on Rails100%",
  "Git IconLearn Git100%",
  "SassLearn Sass20%",
  "JQuery IconjQuery1%",
  "Angular JSLearn AngularJS 1.X100%",
  "Javascript IconLearn JavaScript55%"
]

def string_parser str_arr
  final_array = []
  str_arr.each do |raw_string|
    final_array << raw_string.scan(/\d+/).last.to_i
  end
  final_array
end

Jordan Hudgens

view all post
Leave a comment
Gajanan • 10 months ago

Thank you for all coding exercise/explanation

reply
Jordan Hudgens • 10 months ago

You're welcome, I'm glad you find them helpful!

reply

Please be polite. We appreciate that.

By Daniele Zedda • 18 February

← PREV POST

By Daniele Zedda • 18 February

NEXT POST → 34
Share on