Summary
Build a program that utilizes regular expressions to extract a specific set of integers from a string in Ruby.
Exercise 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
Thank you for all coding exercise/explanation
You’re welcome, I’m glad you find them helpful!
You can simplify this:
def matcher arr
arr.map { |val| val.match(/\d+/)[0] }
end