안전한 탐색 연산자 ruby

코드 예제

1
0

안전한 탐색 연산자에 루비

Scenario
Imagine you have an account that has an owner and you want to get the owner’s address. If you want to be safe and not risk a nil error, you would write something like the following:

if account && account.owner && account.owner.address
...
end
This is really verbose and annoying to type. ActiveSupport includes the try method which has a similar behaviour (but with few key differences that will be discussed later):

if account.try(:owner).try(:address)
...
end
It accomplishes the same thing - it either returns the address or nil if some value along the chain is nil. The first example may also return false if, for example, the owner is set to false.

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
English
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................
Балгарскі
..................................................................................................................
Íslensk
..................................................................................................................