syedsibtain
Wed Sep 25 2024
The
Syntax:
Example:
#ruby #CU6U0R822
dig
method in Ruby is used to safely extract nested values from arrays or hashes. It allows us to traverse a data structure without worrying about whether each level of the structure exists, thus avoiding NoMethodError
exceptions that occur when trying to call methods on nil
.Syntax:
hash_or_array.dig(*keys)
Example:
data = {
user: {
profile: {
name: "John",
age: 30
}
}
}
name = data.dig(:user, :profile, :name) # => "John"
#ruby #CU6U0R822