使用`Hash #fetch`优于`Hash#`的好处

我不确定在什么情况下我会想要使用Hash#fetch over Hash#[] 。 是否有一个常见的场景,它可以很好地使用?

三个主要用途:

  1. 当值是必需的时,即没有默认值:

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

    你也得到一个很好的错误信息:

     key not found: :repeat 
  2. 当值可以为nilfalse ,默认值为其他值:

     if (doit = options.fetch(:repeat, 1)) doit.times{...} else # options[:repeat] is set to nil or false, do something else maybe end 
  3. 如果您不想使用哈希的default / default_proc

     options = Hash.new(42) options[:foo] || :default # => 42 options.fetch(:foo, :default) # => :default 

如果要在密钥不存在时获取默认值或引发错误,则fetch非常有用。 通过将默认值设置为散列,仍然可以不进行fetch ,但是使用fetch ,您可以在现场进行。

但是,您可以这样做:

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

但不是这个:

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

类似地,你可以用Hash#[]改变一个数组

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

但不是用fetch:

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