Just take a note from resources on internet!
1. ActiveRecord
1 2 3 4 5 6 7 8 9 10 11 12 13
| account = Account.new(owner: nil)
account.owner.address
account && account.owner && account.owner.address
account.try(:owner).try(:address)
account&.owner&.address
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| account = Account.new(owner: false)
account.owner.address
account && account.owner && account.owner.address
account.try(:owner).try(:address)
account&.owner&.address
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| account = Account.new(owner: Object.new)
account.owner.address
account && account.owner && account.owner.address
account.try(:owner).try(:address)
account&.owner&.address
|
Catch exception with try!
1 2
| account.try!(:owner).try!(:address)
|
2. Hash
1 2 3 4 5 6 7
| h = { key_1: { key_2: { key_3: "Value" } } }
|
1
| h&.[](:key_1)&.[](:key_2)&.[](:key_3)
|
1
| h.dig(:key_1, :key_2, :key_3)
|
Resources
[1]http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/
[2]https://stackoverflow.com/questions/35922774/safe-navigation-equivalent-to-rails-try-for-hashes