Ruby中的集合编写指南
倾向数组及哈希的字面表示法(除非你需要传递参数到它们的构造函数中)。
#bad arr=Array.new hash=Hash.new #good arr=[] hash={}
当你需要元素为单词(没有空格和特殊符号)的数组的时候总是使用%w的方式来定义字符串数组。应用这条规则仅仅在两个或多个数组。
#bad STATES=['draft','open','closed'] #good STATES=%w(draftopenclosed)
当你需要一个符号的数组(并且不需要保持Ruby1.9兼容性)时,使用%i。仅当数组只有两个及以上元素时才应用这个规则。
#bad STATES=[:draft,:open,:closed] #good STATES=%i(draftopenclosed)
避免在Array或者Hash的最后一项后面出现逗号,特别是当这些条目不在一行。
#bad-easiertomove/add/removeitems,butstillnotpreferred VALUES=[ 1001, 2020, 3333, ] #bad VALUES=[1001,2020,3333,] #good VALUES=[1001,2020,3333]
避免在数组中创造巨大的间隔。
arr=[] arr[100]=1#nowyouhaveanarraywithlotsofnils
当访问一个数组的第一个或者最后一个元素,倾向使用first或last而不是[0]或[-1]。
如果要确保元素唯一,则使用Set代替Array.Set更适合于无顺序的,并且元素唯一的集合,集合具有类似于数组一致性操作以及哈希的快速查找.
尽可能使用符号代替字符串作为哈希键.
#bad hash={'one'=>1,'two'=>2,'three'=>3} #good hash={one:1,two:2,three:3}
避免使用易变对象作为哈希键。
优先使用1.9的新哈希语法当你的哈希键是符号。
#bad hash={:one=>1,:two=>2,:three=>3} #good hash={one:1,two:2,three:3}
在相同的hash字面量中不要混合Ruby1.9hash语法和箭头形式的hash。当你
得到的keys不是符号的时候转换为箭头形式的语法。
#bad {a:1,'b'=>2} #good {:a=>1,'b'=>2}
用Hash#key?不用Hash#has_key?以及用Hash#value?,不用Hash#has_value?Matz提到过长的形式在考虑被弃用。
#bad hash.has_key?(:test) hash.has_value?(value) #good hash.key?(:test) hash.value?(value)
在处理应该存在的哈希键时,使用fetch。
heroes={batman:'BruceWayne',superman:'ClarkKent'} #bad-ifwemakeamistakewemightnotspotitrightaway heroes[:batman]#=>"BruceWayne" heroes[:supermann]#=>nil #good-fetchraisesaKeyErrormakingtheproblemobvious heroes.fetch(:supermann)
在使用fetch时,使用第二个参数设置默认值而不是使用自定义的逻辑。
batman={name:'BruceWayne',is_evil:false} #bad-ifwejustuse||operatorwithfalsyvaluewewon'tgettheexpectedresult batman[:is_evil]||true#=>true #good-fetchworkcorrectlywithfalsyvalues batman.fetch(:is_evil,true)#=>false
尽量用fetch加区块而不是直接设定默认值。
batman={name:'BruceWayne'} #bad-ifweusethedefaultvalue,weeagerevaluateit #soitcanslowtheprogramdownifdonemultipletimes batman.fetch(:powers,get_batman_powers)#get_batman_powersisanexpensivecall #good-blocksarelazyevaluated,soonlytriggeredincaseofKeyErrorexception batman.fetch(:powers){get_batman_powers}
当你需要从一个hash连续的取回一系列的值的时候使用Hash#values_at。
#bad email=data['email'] nickname=data['nickname'] #good email,username=data.values_at('email','nickname')
记住,在Ruby1.9中,哈希的表现不再是无序的.(译者注:Ruby1.9将会记住元素插入的序列)
当遍历一个集合的同时,不要修改这个集合。