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

后端 未结 3 670
花落未央
花落未央 2021-02-12 11:15

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:05

    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.

提交回复
热议问题