问题描述
来自 Ruby Koans about_hashes.rb
:
From Ruby Koans about_hashes.rb
:
在访问散列键时,为什么要使用 #fetch
而不是 #[]
?
Why might you want to use #fetch
instead of #[]
when accessing hash keys?
推荐答案
默认情况下,使用 #[]
将检索哈希值(如果存在),如果不存在则返回 nil *.
By default, using #[]
will retrieve the hash value if it exists, and return nil if it doesn't exist *.
使用 #fetch
为您提供了一些选项(请参阅 #fetch):
Using #fetch
gives you a few options (see the docs on #fetch):
fetch(key_name)
:如果键存在则获取值,如果不存在则引发KeyError
fetch(key_name, default_value)
:如果key存在则取值,否则返回default_value
fetch(key_name) { |key|"default" }
:如果键存在则获取值,否则运行提供的块并返回值.
fetch(key_name)
: get the value if the key exists, raise aKeyError
if it doesn'tfetch(key_name, default_value)
: get the value if the key exists, returndefault_value
otherwisefetch(key_name) { |key| "default" }
: get the value if the key exists, otherwise run the supplied block and return the value.
每一种都应该根据情况使用,但#fetch
功能非常丰富,可以根据使用方式处理多种情况.出于这个原因,我倾向于使用它而不是使用 #[]
访问密钥.
Each one should be used as the situation requires, but #fetch
is very feature-rich and can handle many cases depending on how it's used. For that reason I tend to prefer it over accessing keys with #[]
.
* 正如 Marc-André Lafortune 所说,使用 #[]
访问密钥将调用 #default_proc
(如果存在),否则返回 #default
,默认为 nil
.请参阅::new
的文档条目 了解更多信息.
* As Marc-André Lafortune said, accessing a key with #[]
will call #default_proc
if it exists, or else return #default
, which defaults to nil
. See the doc entry for ::new
for more information.
这篇关于使用哈希时获取与 [] 的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!