在Hash#[]`上使用`Hash#fetch`的好处 [英] Benefits of using `Hash#fetch` over `Hash#[]`
本文介绍了在Hash#[]`上使用`Hash#fetch`的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道在什么情况下我想要使用 Hash#fetch
over Hash#[]
。有没有一个常见的场景,它会很好用?
解决方案
三个主要用途:
-
如果该值是强制性的,即没有默认值:
options.fetch(:repeat).times {...}
不错的错误信息:
键未找到::repeat
false
和默认值是别的:
if(doit = options.fetch(:repeat,1))
doit.times {...}
else
#options [:repeat]设置为nil或false,做别的事情也许
结束
-
当您不想使用
默认
/$ default_proc
一个散列:
options = Hash.new(42)
options [:foo] || :default#=> 42
options.fetch(:foo,:default)#=> :默认
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?
解决方案
Three main uses:
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
When the value can be
nil
orfalse
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
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
这篇关于在Hash#[]`上使用`Hash#fetch`的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文