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

后端 未结 3 1787
别那么骄傲
别那么骄傲 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:08

    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
    
    0 讨论(0)
  • 2021-02-12 12:14

    Three main uses:

    1. When the value is mandatory, i.e. there is no default:

      options.fetch(:repeat).times{...}
      

      You get a nice error message too:

      key not found: :repeat
      
    2. When the value can be nil or false and the default is something else:

      if (doit = options.fetch(:repeat, 1))
        doit.times{...}
      else
        # options[:repeat] is set to nil or false, do something else maybe
      end
      
    3. When you don't want to use the default/default_proc of a hash:

      options = Hash.new(42)
      options[:foo] || :default # => 42
      options.fetch(:foo, :default) # => :default
      
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题