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

后端 未结 3 678
花落未央
花落未央 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:12

    However, you can do this:

    arr = [1,2,3]
    arr[1..-2] #=> [1,2]
    

    But not this:

    arr.fetch(1..-2) #=> TypeError: no implicit conversion of Range into Integer
    

    Similarly you can mutate an array with Hash#[]

    arr[0] = "A"
    arr #=> ["A",2,3]
    

    But not with fetch:

    arr.fetch(0) = "A" #=> unexpected '=', expecting end-of-input
    

提交回复
热议问题