Given:
array = {first: {second: {one: 1, two: 2, three: 3 }}}
assuming anything can be nil
, what would be the simplest/most concise way to access the nested values without tripping over nil? If any of the members doesn't exist, it should just return nil
.
We came up with these:
Pure Ruby:
value = array.fetch(:first, {}).fetch(:second, {}).fetch(:four, nil)
value = begin array[:first][:second][:four]; rescue; end
Ruby on Rails:
value = array.try(:[], :first).try(:[], :second).try(:[], :four)
What can you come up with? Which method would you prefer, and why?
Thanks!