📜  ruby 在调用之前检查 hash 是否有方法 - Ruby 代码示例

📅  最后修改于: 2022-03-11 15:04:45.484000             🧑  作者: Mango

代码示例1
# Use .try(:key) to conditionally access hash keys or methods
attr = my_hash.try(:key1)

# You can chain together multiple try()'s
attr = my_hash.try(:key1).try(:key2)

# If you want to access a value in a hash value you can use ternary operators
attr = my_hash.try(:key1) ? my_hash.key1["key2"] : nil