Skip to main content

Command Palette

Search for a command to run...

Checking for the existence of a Hash key

Published
1 min read

You can test whether a key is present in a hash and return a precise message when it fails thanks to the KeyError exception raised by #fetch:

begin
  {one: "1", two: "2"}.fetch(:three)
rescue => e
  p "The key #{e.key.inspect} cannot be found in #{e.receiver}"
end
# => "The key :three cannot be found in {:one=>\"1\", :two=>\"2\"}"