Created
August 2, 2013 00:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to @johnsyweb for the assist with this