Ruby Hash dig()函数
Hash#dig()是一个Hash类方法,它通过在每一步调用dig来找到由key对象的序列指定的嵌套值。
语法。Hash.dig()
参数:哈希值
返回:通过每一步调用dig,找到由key对象的序列指定的嵌套值,否则为nil
例子 #1 :
# Ruby code for Hash.dig() method
# declaring Hash value
a = {a:100, b:200}
# declaring Hash value
b = {a:100, c:300, b:200}
# declaring Hash value
c = {a:100}
# Dig Value
puts "Hash a dig form : #{a.dig(:a)}\n\n"
puts "Hash b dig form : #{b.dig(:c)}\n\n"
puts "Hash c dig form : #{c.dig(:a)}\n\n"
输出:
Hash a dig form : 100
Hash b dig form : 300
Hash c dig form : 100
例子 #2 :
# Ruby code for Hash.dig() method
# declaring Hash value
a = { "a" => 100, "b" => 200 }
# declaring Hash value
b = {"a" => 100}
# declaring Hash value
c = {"a" => 100, "c" => 300, "b" => 200}
# Dig Value
puts "Hash a dig form : #{a.dig("a")}\n\n"
puts "Hash b dig form : #{b.dig("a")}\n\n"
puts "Hash c dig form : #{c.dig("b")}\n\n"
输出:
Hash a dig form : 100
Hash b dig form : 100
Hash c dig form : 200