Forum: Ruby on Rails nested hash and nil question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Scott N. (Guest)
on 2009-05-12 09:54
(Received via mailing list)
i need to pull out some specific values from a nested hash, but nils
are driving me crazy. in the following example, if address_details,
country, administrative_area, locality OR postal_code are nil i get
"The error occurred while evaluating nil.[]"

zip = placemark['address_details']['country']['administrative_area']

i tried

unless placemark['address_details']['country']['administrative_area']

but if anything above postal_code_number is nil i still get the error.
i could check each level but that is really ugly.

is there a easy way to check if postal_code_number exists?
Ryan W. (Guest)
on 2009-05-12 11:02
(Received via mailing list)
What value should 'zip' contain if postal_code_number doesn't exist (or
of the keys above it)?

If one of the keys in that long nasty chain are nil, you're going to get
exception, but if you know an acceptable default value in case you can't
eval the whole expression, rescue the exception and return what you

If you want it to be an empty string, for instance, you could do:

zip =
rescue ''
Scott N. (Guest)
on 2009-05-12 18:25
(Received via mailing list)
that will work perfect, thanks
This topic is locked and can not be replied to.