To the bewilderment of my friends and co-workers, regex (or regular expression)is one of my favorite things in the world. Not only is writing them fun (think ciphers!), but they can be extremely useful as well! Today we're going to see how we can use it to help out our pal Santa Clause.
Before we get started... What is regex?: a sequence of characters that define a search pattern. A lot of programming languages either have regex built in or usable through libraries. Today we're going to use Ruby!
- Why is it useful?: When we use regex to define a search pattern, we can save ourselves a ton of time. It's efficient to write and efficient to run.
We all know that Santa Clause is an incredibly busy man. His eyesight isn't what it used to be though. (He still knows who has been behaving though!) This year the elves forgot to split the list into two, one for nice children and one for naughty. Santa needs our help to see who all of the good children are before he heads out to deliver toys.
Let's say this is our list of children:
all_kids = "Ronnie - Nice, Candice - Nice, Michael - Naughty, Elsa - Naughty, Blake - Nice, Jer - Nice, Helen - Naughty, Anthony - Nice, Nicholas - Naughty, Joseph - Naughty"
Santa would like to know how many nice children are on the list this year so he can make sure that he's got enough time to get to everyone.
We can use Ruby's .scan
method for this one. It will return an array of each occurrence of our search pattern.
def nice_length(kids)
kids.scan(/\b(nice)/i).length
end
nice_length(all_kids)
would return 5
. Neat!
Santa asks us to give him a list of only the nice children so that he can make sure all of the gift tags are correct.
all_kids = ["Ronnie - Nice", "Candice - Nice", "Michael - Naughty", "Elsa - Naughty", "Blake - Nice", "Jer - Nice", "Helen - Naughty", "Anthony - Nice", "Nicholas - Naughty", "Joseph - Naughty"]
def nice_list(kids)
kids.map{|kid| kid if kid.match(/\b(nice)/i)}
end
Running this method returns this array: ["Ronnie - Nice", "Candice - Nice", "Blake - Nice", "Jer - Nice", "Anthony - Nice"]
Awesome! We just made Santa's job way easier. Hopefully this keeps us on the nice list for next year!
Here are two great resources for practicing regex: Rubular.com and Regular-Expressions.info.
Top comments (0)