We’re wrapping up week 4 at the Flatiron School and… I’m starting to work on a fun gem idea! Yes, I’ve been inspired by my classmates to take the plunge and build my own Ruby gem.
But first things first. I need data in order for my gem to be useful. So earlier today (well, yesterday, at this point) — I proceeded to scrape some data. And in the process, I discovered a neat pair of methods that work very nicely together: .zip and Hash.
WHAT DOES .ZIP DO?
The .zip method basically joins two arrays together, pairing elements from each that have matching indexes and returning the whole thing as a big array that contains mini-arrays populated with the newly paired elements. You set one of the arrays as the receiver of the method, which then takes the second array as an argument. It looks something like this:
Not too complicated, right?
Here it is in action:
WHAT DOES HASH DO?
The Hash class method is SO cool. You can basically dump the whole
array1.zip(array2) sequence inside of the [brackets], like so:
What do you think this will result in?
Only one way to find out!
How crazy awesome is that?! It returned a hash and populated it with key-value pairs made out of the elements from each array that have matching index numbers.
So the .zip and Hash methods, together, proved very useful indeed as I scraped data from Billboard.com and was able to get
songs, separately, to look like a numbered list of the pair,
artist - song. And that’s all I’m saying about my gem-in-progress, for now!
I <3 Ruby.
- You can join two arrays together and return matching-index pairs using
- You can create a hash populated with key-value pairs made out of two arrays using
Make yourself useful.