Today I Learned

hashrocket A Hashrocket project

Extract all keys and values from a Hash in Ruby

My first attempt was to just concatenate all the keys and values:

hash = {a: 1, b: 2}
hash.keys + hash.values
 => [:a, :b, 1, 2]

Ruby always surprises me. There is always a method that does exactly what you need.

So I thought, what about I just call flatten, will it work?

 => [:a, 1, :b, 2]

❤️❤️❤️ And it does. ❤️❤️❤️

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.