红宝石 |哈希 flatten()函数
Hash#flatten()是一个 Hash 类方法,它返回一维展平散列数组。
Syntax: Hash.flatten()
Parameter: Hash values
Return: one-dimensional flattening hash array
示例 #1:
# Ruby code for Hash.flatten() method
# declaring Hash value
a = {a:100, b:200}
# declaring Hash value
b = {a:100, c:[300, 45], b:200}
# declaring Hash value
c = {a:100}
# flatten Value
puts "Hash a flatten form : #{a.flatten()}\n\n"
puts "Hash b flatten form : #{b.flatten()}\n\n"
puts "Hash c flatten form : #{c.flatten()}\n\n"
输出 :
Hash a flatten form : [:a, 100, :b, 200]
Hash b flatten form : [:a, 100, :c, [300, 45], :b, 200]
Hash c flatten form : [:a, 100]
示例 #2:
# Ruby code for Hash.flatten() method
# declaring Hash value
a = { "a" => 100, "b" => 200 }
# declaring Hash value
b = {"a" => 100}
# declaring Hash value
c = {"a" => 100, "c" => [300, 200, 500], "b" => 200}
# flatten Value
puts "Hash a flatten form : #{a.flatten()}\n\n"
puts "Hash b flatten form : #{b.flatten()}\n\n"
puts "Hash c flatten form : #{c.flatten()}\n\n"
输出 :
Hash a flatten form : ["a", 100, "b", 200]
Hash b flatten form : ["a", 100]
Hash c flatten form : ["a", 100, "c", [300, 200, 500], "b", 200]