Lets assume we send a request and get the following response as JSON
user = {
user: {
address: {
street: '123 Some street'
}
}
}
Now in order to get the street address, the simplest way would be street = user[:user][:address][:street]
but what if address
is empty or even the user
object is empty.
In order to avoid the error sometimes we end up writing code which looks like
if user[:user] && user[:user][:address] && user[:user][:address][:street]
street = user[:user][:address][:street]
end
The above code is valid, but looks quite ugly. With ruby a less known functionality is hash.dig
. As mentioned in ruby docs dig
Retrieves the value object corresponding to the each key objects repeatedly.
So, if we use dig in the above example it becomes
street = user.dig(:user, :address, :street) || 'Default Street'
Cheers
Top comments (0)