Useful Ruby (and Rails) Hash Methods

Been pretty busy this past year (so much for trying to make an effort to post more :-/). Thought I make a quick post about some useful hash methods that I've been using lately.

For this post, I'll be calling methods against the following hash structure.

my_hash = { test: 'Test', this: 'This', out: 'Out' }


I've been using fetch to provide default values for keys that are not provided in hash. It can be really useful for parameters passed in to methods. I mostly provide a default value, but if you don't provide one a KeyError exception will be thrown, which could be useful.

my_hash.fetch(:test, 'Default') # => 'Test'
my_hash.fetch(:other, 'Other Default') # => 'Other Default'
my_hash.fetch(:something') # => throws KeyError

This is also useful for values that should be boolean. For instance:

my_hash[:conditional] # => nil
my_hash.fetch(:conditional, false) # => produces false not nil
my_hash[:conditional] = true
my_hash.fetch(:conditional, false) # => true


values_at is useful to select a subset of the values from the hash given a list of keys.

my_hash.values_at(:test, :this) # => ['Test', 'This']

Rails Hash Methods

I'd also like to point out a few Hash methods that I've been using quite a bit on the Rails end, slice and except.


slice returns a new Hash containing only the keys passed in as the arguments.

my_hash.slice(:test) # => { test: 'Test' }


except is the inverse of slice. except returns a new Hash that contains all of the key pairs except for the keys passed in as the argument.

my_hash.except(:test) # => { this: 'This', out: 'Out' }

I've been utilizing these methods when working on building up a filter set for queries.

As I mentioned, these are just some methods that I've been using a lot recently. If anyone has any other methods they find useful feel free to drop a comment.