Photo by Weber VanHeber from FreeImages
This mini post is a follow up to the Hash-tastic! series.
You can find it here: https://dev.to/leighad/hash-tastic-part-one-1706
In that series, I presented a nested data structure and discussed how to extract the data within it. I did not use any built in Ruby methods, but instead I chose to write all the code out for purposes of learning.
Here I would like to show a quick and easy way to use a built-in Ruby method to pull out this data. While built-in methods are quite handy and certainly can save time and lines of code, it is really important to understand what is going on behind all that 'magic'. There are so many good ones to choose from, but for this example, we will look a bit closer at Ruby's values_at method.
Say you have an array:
arr = ['cat', 'dog', 'bird', 'fish', 'rabbit']
You could get multiple non-sequential values this way:
x, y, z = arr[0], arr[1], arr[3]
Or you could just use the values_at method:
x, y, z = arr.values_at(0, 1, 3)
This would return the values of elements 0, 1, 3 which are cat, dog, fish
You can also use values_at with a hash:
candy_hash = {gummies: 5, sours: 7, chocolate: 10}
Here you could write:
candy_hash.values_at(sours:)
This would return the value of sours: which is 7
As you can see, built-in methods can be quick and easy to use. It is tempting to grab one when you need that quick fix, but just make sure you really understand what is happening behind all that Ruby 'magic'!
Top comments (0)