Let's hash this out
Comparing Ruby arrays and hashes
4/1/2015
Arrays are dumb and hashes are smart. Well, maybe that's not the best way to put it. Arrays are simple and hashes are complicated.
That sounds better.
There are plenty of great uses for arrays. When you've got a simple set of data you can push it into an array and use it as you wish.
Let's say you want to use the years Babe Ruth played in the majors. That array would look like this:
babe_years = [1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935]
Super simple. A list of years. If you wanted to know what the year was during Babe Ruth's 20th season you would just do babe_years[19]
(arrays start counting at 0, so the 20th season is at index 19). That search of the array would return 1933
.
Cool, Babe Ruth's 20th season was in 1933.
But there's a lot more to Babe Ruth than the years he played. There's the years he was an All-Star, the years he was an MVP, the years he lead the league in home runs, and on and on and on.
We could create a new array for each of these little groups of years.
babe_mvp_years = [1923]
babe_allstar_years = [1933, 1934]
babe_hrleader_years = [1918, 1919, 1920, 1921, 1923, 1924, 1926, 1927, 1928, 1929, 1930, 1931]
Yeah, Babe only won one MVP. Also, the All-Star Game didn't start until 1933.
We're starting to build up a decent profile on Babe Ruth. What if we wanted to have access to his full name, his jersey number, height and weight as well?
Theres a way to package all of these things together into one object in Ruby, it's called a hash.
Pulling everything into a hash will give us some standardization and readability. It's a great way to save this complicated data set we're building.
There are a shitload of ways to build a hash, but for this example I'm going to create it literally and use the GitHub Ruby style guide.
Alrighty, Babe, here we go:
Sweet! So now our hash includes all the great stuff that we figured out at the beginning of this blog and more. The items on the left side of =>
inside the hash, like :jersey_number
are called keys. And the values on the right side of the =>
are called values. More specifically, the keys are symbols because they have the :
at the start. You can also use strings as keys.
Notice how we have strings and arrays as values inside our hash.
To access the values inside our hash we can run some pretty simple code that is much like accessing an array: babe_ruth[:jersey_number]
will return "3"
Let's try our example from up above and see what year it was during Babe's 20th season: babe_ruth[:years][19]
Yep, we get 1933
just like above!