本文簡要介紹ruby語言中 Hash.transform_keys
的用法。
用法
transform_keys {|key| ... } → new_hash
transform_keys(hash2) → new_hash
transform_keys(hash2) {|other_key| ...} → new_hash
transform_keys → new_enumerator
返回一個新的 Hash 對象;每個條目都有:
-
塊提供的 key 。
-
self
中的值。
可以提供一個可選的散列參數來將鍵映射到新鍵。任何未給出的鍵都將使用提供的塊進行映射,或者如果沒有給出塊則保持不變。
變換鍵:
h = {foo: 0, bar: 1, baz: 2}
h1 = h.transform_keys {|key| key.to_s }
h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
h.transform_keys(foo: :bar, bar: :foo)
#=> {bar: 0, foo: 1, baz: 2}
h.transform_keys(foo: :hello, &:to_s)
#=> {:hello=>0, "bar"=>1, "baz"=>2}
覆蓋重複鍵的值:
h = {foo: 0, bar: 1, baz: 2}
h1 = h.transform_keys {|key| :bat }
h1 # => {:bat=>2}
如果沒有給出塊,則返回一個新的枚舉器:
h = {foo: 0, bar: 1, baz: 2}
e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
h1 = e.each { |key| key.to_s }
h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
相關用法
- Ruby Hash.transform_keys用法及代碼示例
- Ruby Hash.transform_values!用法及代碼示例
- Ruby Hash.transform_values用法及代碼示例
- Ruby Hash.to_s用法及代碼示例
- Ruby Hash.to_a用法及代碼示例
- Ruby Hash.to_proc用法及代碼示例
- Ruby Hash.to_h用法及代碼示例
- Ruby Hash.reject用法及代碼示例
- Ruby Hash.delete()用法及代碼示例
- Ruby Hash.new用法及代碼示例
- Ruby Hash.size用法及代碼示例
- Ruby Hash.delete用法及代碼示例
- Ruby Hash.hash <=用法及代碼示例
- Ruby Hash.select!用法及代碼示例
- Ruby Hash.ruby2_keywords_hash用法及代碼示例
- Ruby Hash.rassoc(obj)用法及代碼示例
- Ruby Hash.values_at()用法及代碼示例
- Ruby Hash.fetch_values()用法及代碼示例
- Ruby Hash.select用法及代碼示例
- Ruby Hash.initialize_copy用法及代碼示例
- Ruby Hash.replace用法及代碼示例
- Ruby Hash.merge!用法及代碼示例
- Ruby Hash.delete_if用法及代碼示例
- Ruby Hash.slice用法及代碼示例
- Ruby Hash.hash用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Hash.transform_keys。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。