There’s several strategies here depending a lot on context.
If your value is indeed nilable and you should be handling the nil case on the call side, do so:
if common = cfg.common
puts "common is not set"
The compiler cannot guarantee that two subsequent calls to a method return the same value, so you have to assign the return value of the call to a local variable.
If progressing with
nil when a part of the chain is
nil is your way to go,
try is your friend:
puts cfg.common.try &.value("key_1")
You could also alter the definition of
common, to have
common be not nilable, and a runtime error if it is after all, and
common? be the nilable variant. This pattern is implemented by the
getter! common = maybe_set_a_value
puts cfg.common.value("key_1") unless cfg.common?
A shortcut to implementing the “raise on nil” behavior is calling
.not_nil!, so the above is equivalent to
@common = maybe_set_a_value