本文簡要介紹ruby語言中 Hash.flatten
的用法。
用法
flatten → new_array
flatten(level) → new_array
返回一個新的 Array 對象,它是 self
的一維展平。
默認情況下,嵌套數組不會展平:
h = {foo: 0, bar: [:bat, 3], baz: 2}
h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
從整數參數 level
獲取遞歸展平的深度:
h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
當level
為負數時,展平所有嵌套數組:
h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
當 level
為零時,返回等效於 to_a
:
h = {foo: 0, bar: [:bat, 3], baz: 2}
h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
h.flatten(0) == h.to_a # => true
相關用法
- Ruby Hash.flatten用法及代碼示例
- Ruby Hash.fetch_values()用法及代碼示例
- Ruby Hash.fetch()用法及代碼示例
- Ruby Hash.fetch_values用法及代碼示例
- Ruby Hash.fetch用法及代碼示例
- Ruby Hash.filter用法及代碼示例
- Ruby Hash.filter!用法及代碼示例
- 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.to_s用法及代碼示例
- Ruby Hash.values_at()用法及代碼示例
- 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.flatten。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。