Câu hỏi phỏng vấn Ruby
Câu hỏi

Why might you use Hash#fetch over Hash#[] when querying values in a hash?

Câu trả lời

When deciding whether to use Hash#fetch over Hash#[] for querying values in a Ruby hash, there are several reasons why Hash#fetch might be preferred:

  1. Error Handling: Hash#fetch raises a KeyError if the specified key is not found in the hash unless a default value is provided. This behavior is useful for debugging and for cases where keys are expected to always exist. If a key is critical to the operation, using fetch can help identify problems early by failing loudly and clearly[1][3][5][6].

  2. Default Values: Hash#fetch allows you to specify a default value that will be returned if the specified key is not found. This can be done either directly as an argument or through a block that is only executed if the key is missing. This is particularly useful when you want to compute the default value only if necessary, avoiding potentially expensive operations if the key exists[1][3][5][6].

  3. Clarity and Intent: Using Hash#fetch can make the code more readable by explicitly stating that a key is expected to exist. It avoids the ambiguity of Hash#[], which returns nil both when the key is not found and when the key’s value is actually nil. This clarity ensures that the presence of a key is a deliberate and clear requirement in the code logic[1][3][5][6].

  4. Avoiding Unintended Defaults: With Hash#[], if the key is not found, nil is returned, which might be indistinguishable from a valid nil value stored in the hash. Hash#fetch helps differentiate between a missing key and a key with a nil value, thus avoiding confusion and potential bugs in the program logic[1][3][5][6].

  5. Performance Considerations: In some versions of Ruby, Hash#fetch has been optimized to be as fast as or faster than Hash#[], especially when including a default value. This makes `...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

Why might you want to alias a method?

middle

What is the difference between Kernel#require and Kernel#load ?

middle

What is a Proc?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào