Elegantly handling blank values in a nested hash

ruby, ruby-on-rails

Solution

`#fetch` is your friend:

my_hash.fetch(:parent, {})[:child].blank?

Problem

I'm sure I've seen an elegant solution to this before, but I can't quite find it: I have a rails controller which may-or-may-not have the following hash element: ``` myhash[:parent_field] ``` Inside that parent field, a child element could also be blank. I'm currently checking that via the (very ugly) method: ``` if (!myhash[:parent_field] || !myhash[:parent_field][:child_field] || myhash[:parent_field][:child_field].blank?) ``` Which works, but I figure - surely - there has to be a more elegant way. Just to reiterate: - myhash[:parent_field] may or may not exist - If it does exist, myhash[:parent_field][:child_field] may or may not exist - If that exists, it may or may not be blank.

Original source

Related problems