本文簡要介紹ruby語言中 Hash[]
的用法。
用法
Hash[] → new_empty_hash
Hash[hash] → new_hash
Hash[ [*2_element_arrays] ] → new_hash
Hash[*objects] → new_hash
返回一個用給定對象(如果有)填充的新 Hash 對象。見 Hash::new
。
不帶參數,返回一個新的空哈希。
當單個給定參數是 Hash 時,返回一個新 Hash,其中填充了給定 Hash 中的條目,不包括默認值或 proc。
h = {foo: 0, bar: 1, baz: 2}
Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
當單個給定參數是 2 元素數組的 Array 時,返回一個新的 Hash 對象,其中每個 2 元素數組形成一個鍵值條目:
Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
當參數計數為偶數時;返回一個新的 Hash 對象,其中每個連續的參數對都成為鍵值條目:
Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
如果參數列表不符合上述任何一項,則引發異常。
相關用法
- Ruby Hash.reject用法及代碼示例
- Ruby Hash shift()用法及代碼示例
- Ruby Hash.delete()用法及代碼示例
- Ruby Hash length()用法及代碼示例
- Ruby Hash.new用法及代碼示例
- Ruby Hash.size用法及代碼示例
- Ruby Hash rehash用法及代碼示例
- Ruby Hash.delete用法及代碼示例
- Ruby Hash.hash <=用法及代碼示例
- Ruby Hash size()用法及代碼示例
- Ruby Hash each_pair()用法及代碼示例
- Ruby Hash.select!用法及代碼示例
- Ruby Hash value?用法及代碼示例
- Ruby Hash values用法及代碼示例
- Ruby Hash.ruby2_keywords_hash用法及代碼示例
- Ruby Hash.rassoc(obj)用法及代碼示例
- Ruby Hash.to_s用法及代碼示例
- Ruby Hash.values_at()用法及代碼示例
- Ruby Hash.fetch_values()用法及代碼示例
- Ruby Hash.select用法及代碼示例
- Ruby Hash.initialize_copy用法及代碼示例
- Ruby Hash.replace用法及代碼示例
- Ruby Hash member?用法及代碼示例
- Ruby Hash each_key用法及代碼示例
- Ruby Hash dig()用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Hash[]。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。