What is the difference between calling .fetch() on a Hash vs simply calling its key?
Question: What is the difference between using .fetch() on a hash rather than just hash_object[:key]? They both do the same thing, right?
Consider the following hash:
h = {:a=>1, :b=>2}
Ok you have two choices to extract the value associated with the :a key:
h[:a]
# or another choice:
h.fetch(:a)
# what's the difference?
Well in this case, they both produce the same answer. But what if :a does not exist in the hash?
If :a doesn’t exist, then fetch will throw an error, but invoking h[:a] – things fail silently: you get nil as a returned value. So you’re not quite sure whether :a exists as a key in the hash, or whether the value of :a in the hash (if it does exist) is nil. And remember, in Ruby, nil is an object. Everything is an object in Ruby.
Written on February 7, 2017