Retrieving Values from Hashes

In Ruby, there are at least two ways to get a specific value from a hash with two different results if the key is not found.

1. Hash#fetch

h = { "a" => 100, "b" => 200 }
h.fetch("z")
=> KeyError: key not found: "z"from (pry):26:in `fetch'

2. hsh[key] → value

h = { "a" => 100, "b" => 200 }
h["z"]
=> nil

Which one you want to use depends on whether you want to raise an error if it doesn’t exist or just check if it is nil.