我从
RubyKoans开始经历about_hashes.rb.1练习让我感到困惑:
def test_default_value hash1 = Hash.new hash1[:one] = 1 assert_equal 1,hash1[:one] #ok assert_equal nil,hash1[:two] #ok hash2 = Hash.new("dos") hash2[:one] = 1 assert_equal 1,hash2[:one] #ok assert_equal "dos",hash2[:two] #hm? end
我的猜测是Hash.new(“dos”)使“dos”成为所有不存在键的默认答案.我对吗?
解决方法
是的,你是对的,看起来ruby公司有一个错误,hash2 [:two]将返回“dos”
new → new_hash@H_403_14@ new(obj) → new_hash@H_403_14@ new {|hash,key| block } → new_hash
Returns a new,empty hash. If this hash is subsequently accessed by a@H_403_14@ key that doesn’t correspond to a hash entry,the value returned@H_403_14@ depends on the style of new used to create the hash. In the first@H_403_14@ form,the access returns nil. If obj is specified,this single object@H_403_14@ will be used for all default values. If a block is specified,it will@H_403_14@ be called with the hash object and the key,and should return the@H_403_14@ default value. It is the block’s responsibility to store the value in@H_403_14@ the hash if required.