Hash.flatten 方法
在本文中,我們將研究 Hash.flatten 方法。這種方法的用法原理可以通過它的名字來預測,但它並不像看起來那麽簡單。那麽,我們將在其餘內容中借助其語法和程序代碼來理解該方法。
方法說明:
該方法是Ruby 庫中專門為Hash 類定義的公共實例方法。此方法的用法方式是在展平整個哈希對象後返回一個數組對象。這意味著每個鍵值對都將被轉換為一個數組對象,或者您可以說它將成為 Array 對象的一個單獨元素。此方法是一種非破壞性方法,這意味著此方法創建的更改不會影響實際的哈希實例。
用法:
Hash_object.flatten or Hash_object.flatten(level)
所需參數:
這個方法隻接受一個參數,這個參數隻不過是你想要對散列對象做的扁平化級別。
範例1:
=begin
Ruby program to demonstrate flatten method
=end
hash1={"color"=>"Black","object"=>["car","phone"],"love"=>["mom","friends"],"fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash.flatten implementation"
ary = hash1.flatten
puts "Hash object after flatten:#{ary}"
puts "Self hash object:#{hash1}"
輸出
Hash.flatten implementation Hash object after flatten:["color", "Black", "object", ["car", "phone"], "love", ["mom", "friends"], "fruit", "Kiwi", "vege", "potato"] Self hash object:{"color"=>"Black", "object"=>["car", "phone"], "love"=>["mom", "friends"], "fruit"=>"Kiwi", "vege"=>"potato"}
說明:
在上麵的代碼中,您可以觀察到我們在 Hash.flatten 方法的幫助下扁平化了哈希對象。第一級扁平化已經完成,其中所有散列元素現在都是數組的一部分。您可以看到此方法不會對實際散列產生任何影響,因為此方法是非破壞性方法的示例之一。
範例2:
=begin
Ruby program to demonstrate flatten method
=end
hash1={"color"=>"Black","object"=>["car","phone"],"love"=>["mom","friends"],"fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash.flatten implementation"
puts "Enter the level of flatten"
lvl = gets.chomp.to_i
ary = hash1.flatten(lvl)
puts "Hash object after flatten:#{ary}"
puts "Self hash object:#{hash1}"
輸出
Hash.flatten implementation Enter the level of flatten 2 Hash object after flatten:["color", "Black", "object", "car", "phone", "love", "mom", "friends", "fruit", "Kiwi", "vege", "potato"] Self hash object:{"color"=>"Black", "object"=>["car", "phone"], "love"=>["mom", "friends"], "fruit"=>"Kiwi", "vege"=>"potato"}
說明:
在上麵的代碼中,您可以觀察到我們在 Hash.flatten 方法的幫助下扁平化了哈希對象。第二級扁平化已經完成,其中所有散列元素現在都是數組的一部分。您可以看到此方法不會對實際散列產生任何影響,因為此方法是非破壞性方法的示例之一。
相關用法
- Ruby Hash.fetch_values()用法及代碼示例
- Ruby Hash.fetch()用法及代碼示例
- Ruby Hash.rassoc(obj)用法及代碼示例
- Ruby Hash.keep_if用法及代碼示例
- Ruby Hash.delete_if用法及代碼示例
- Ruby Hash.each用法及代碼示例
- Ruby Hash.keys用法及代碼示例
- Ruby Hash.transform_keys用法及代碼示例
- Ruby Hash.each_key用法及代碼示例
- Ruby Hash.insert()用法及代碼示例
- Ruby Hash.values_at()用法及代碼示例
- Ruby Hash.rehash用法及代碼示例
- Ruby Hash.each_value用法及代碼示例
- Ruby Hash.values用法及代碼示例
- Ruby Hash.replace()用法及代碼示例
- Ruby Hash.compact用法及代碼示例
- Ruby Hash.reject用法及代碼示例
- Ruby Hash.assoc()用法及代碼示例
- Ruby Hash.select用法及代碼示例
- Ruby Hash.invert用法及代碼示例
注:本文由純淨天空篩選整理自 Hash.flatten Method with Example in Ruby。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。