ruby 使用哈希时获取与 [] 的比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16569409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fetch vs. [] when working with hashes?
提问by allanberry
From Ruby Koans about_hashes.rb:
来自 Ruby Koans about_hashes.rb:
Why might you want to use #fetchinstead of #[]when accessing hash keys?
为什么在访问哈希键时要使用#fetch而不是使用#[]?
回答by Jon Cairns
By default, using #[]will retrieve the hash value if it exists, and return nil if it doesn't exist *.
默认情况下,#[]如果存在,则使用将检索哈希值,如果不存在则返回 nil *。
Using #fetchgives you a few options (see the docs on #fetch):
Using#fetch为您提供了一些选项(请参阅#fetch上的文档):
fetch(key_name): get the value if the key exists, raise aKeyErrorif it doesn'tfetch(key_name, default_value): get the value if the key exists, returndefault_valueotherwisefetch(key_name) { |key| "default" }: get the value if the key exists, otherwise run the supplied block and return the value.
fetch(key_name): 如果键存在则获取值,KeyError如果不存在则提高afetch(key_name, default_value): 如果键存在则获取值,default_value否则返回fetch(key_name) { |key| "default" }:如果键存在则获取值,否则运行提供的块并返回值。
Each one should be used as the situation requires, but #fetchis 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 #[].
每一种都应根据情况需要使用,但#fetch功能非常丰富,可以根据使用方式处理多种情况。出于这个原因,我倾向于使用它而不是使用#[].
* As Marc-André Lafortune said, accessing a key with #[]will call #default_procif it exists, or else return #default, which defaults to nil. See the doc entry for ::newfor more information.
* 正如 Marc-André Lafortune 所说,访问密钥 with#[]将调用(#default_proc如果存在),否则返回#default,默认为nil。有关 更多信息,请参阅文档条目::new。
回答by J?rg W Mittag
With [], the creator of the hash controls what happens when a key does not exist, with fetchyou do.
使用[],散列的创建者控制当键不存在时会发生什么,而fetch您则可以。
回答by Sergio Tulentsev
fetchby default raises an error if the key is not found. You can supply a default value instead.
fetch如果未找到密钥,默认情况下会引发错误。您可以改为提供默认值。
h = {}
h.fetch(:foo) # no default value, raises error
# => # ~> -:3:in `fetch': key not found: :foo (KeyError)
h.fetch(:bar, 10) # default value, returns default value
# => 10

