Ruby Hash flatten()函数
Hash#flatten()是一个Hash类方法,用于返回一维扁平化的哈希数组。
语法。Hash.flatten()
参数:哈希值
返回:一维扁平化的哈希数组
例子 #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]