Benefits of using `Hash#fetch` over `Hash#[]`

后端 未结 3 1793
别那么骄傲
别那么骄傲 2021-02-12 11:50

I am not sure in what situation I would want to use Hash#fetch over Hash#[]. Is there a common scenario in where it would be of good use?

3条回答
  •  忘掉有多难
    2021-02-12 12:23

    When you want to get a default value or raise an error when the key does not exist, fetch is useful. It is still possible to do so without fetch by setting the default value to the hash, but using fetch, you can do it on the spot.

提交回复
热议问题