在Hash#[]`上使用`Hash#fetch`的好处 [英] Benefits of using `Hash#fetch` over `Hash#[]`

查看:88
本文介绍了在Hash#[]`上使用`Hash#fetch`的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道在什么情况下我想要使用 Hash#fetch over Hash#[] 。有没有一个常见的场景,它会很好用?

解决方案

三个主要用途:


  1. 如果该值是强制性的,即没有默认值:

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

    不错的错误信息:

     键未找到::repeat 
    nil 或 false 和默认值是别的:

      if(doit = options.fetch(:repeat,1))
    doit.times {...}
    else
    #options [:repeat]设置为nil或false,做别的事情也许
    结束


  2. 当您不想使用默认 / $ 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:

  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
    

这篇关于在Hash#[]`上使用`Hash#fetch`的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆