So, lately I've been learning the Ruby programming language. As a complete beginner it's important to learn and apply the foundational concepts in order to succeed at programming. Therefore, I've been completing all of my module assignments in order to be best prepared for success as a full stack developer. Today, I was working on the "Character Types" assignment where I was tasked with writing a program that takes a randomly sampled string and outputs the total number of letters, spaces, and digits in the given string.
strings = [
"here 12 plus 25",
"puzzle number 04 ",
" "
]
string = strings.sample
pp string
I used regular expressions (regexp), the .scan method, and the .length method to make that possible.
Regular expressions are a sequence of characters that match a string. They are very useful for extracting information from a string or when you're using the .gsub method to replace information inside of a string.
In this example:
letter_count = string.scan(/[A-za-z]/).length
pp "Number of letters in the string is: #{letter_count}"
space_count = string.scan(/\s/).length
pp "Number of spaces in the string is: #{space_count}"
digit_count = string.scan(/\d/).length
pp "Number of digits in the string is: #{digit_count}"
I wanted to get the letter count, space count, and digit count of the randomly outputted string. So in order to do so, I used the .scan() method to iterate through the strings and regular expression arguments (/[A-za-z]/)
which matches all capital and lowercase letters, (/\s/) which matches all spaces, and (/\d/) which matches all digits.
Top comments (3)
I also found gsub method and regex incredibly useful in ruby. I found myself asking questions to chatgpt about regex in javascript, and discovered that regex can be used with the following javascript methods (.test, .replace, .split, and .match)
Hi Alana, be careful when dealing with regex :)
There is this quote that said
In this way, I suggest you to use rubular.com/ in order to check your regexes :)
Hi V,
Thank you for your comment! I took your advice and was able to check that all of the regexes worked on the randomly sampled strings.
strings = [
"here 12 plus 25",
"puzzle number 04 ",
" "
]
string = strings.sample