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.
Related problems
- Ruby - Access multidimensional hash and avoid access nil object
- How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?
- Is there a clean way to avoid calling a method on nil in a nested params hash?
- Ruby: Nils in an IF statement
- How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?