Today I Learned

hashrocket A Hashrocket project

Default Hash values are super easy in Ruby

Want a list?

list_default = Hash.new([])

That's pretty darn easy.

Edit: Thanks to @kaokun on twitter for catching this and correcting me. This will return the same array each time (having flashbacks to the first time I used mutable keyword args in python). To get a different array, you need need to pass a block with the behavior:

list_default = Hash.new { |hash, key| hash[key] = [] }

Just because your language hides pointers and references doesn't mean you can ignore them I guess.

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.