heroes={batman:'Bruce Wayne',superman:'Clark Kent'}# bad - if we make a mistake we might not spot it right awayheroes[:batman]# => "Bruce Wayne"heroes[:supermann]# => nil# good - fetch raises a KeyError making the problem obviousheroes.fetch(:supermann)
在使用 fetch 時,使用第二個參數設置默認值而不是使用自定義的邏輯。
1234567
batman={name:'Bruce Wayne',is_evil:false}# bad - if we just use || operator with falsy value we won't get the expected resultbatman[:is_evil]||true# => true# good - fetch work correctly with falsy valuesbatman.fetch(:is_evil,true)# => false
盡量用 fetch 加區塊而不是直接設定默認值。
12345678
batman={name:'Bruce Wayne'}# bad - if we use the default value, we eager evaluate it# so it can slow the program down if done multiple timesbatman.fetch(:powers,get_batman_powers)# get_batman_powers is an expensive call# good - blocks are lazy evaluated, so only triggered in case of KeyError exceptionbatman.fetch(:powers){get_batman_powers}