Skip to content

Instantly share code, notes, and snippets.

@sevaine
Created August 2, 2013 00:40
Show Gist options
  • Save sevaine/6136647 to your computer and use it in GitHub Desktop.
Save sevaine/6136647 to your computer and use it in GitHub Desktop.
Raising an exception in ruby when a hash does not contain all required ( expected ) keys
#
# approach 1
#
expected_keys = { :a, :b, :c }
sample_hash = { a: 1, b: 2 }
begin
expected_keys.each { |k| raise StandardError, "#{k} not found" unless sample_hash.has_key? k }
rescue StandardError => e
puts e
end
#
# Approach 2
#
def hash_has_all_keys(hash_to_check, expected_keys)
expected_keys.all? { |k| hash_to_check.fetch(k) }
rescue KeyError => e
puts e
end
@sevaine
Copy link
Author

sevaine commented Aug 2, 2013

Thanks to @johnsyweb for the assist with this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment