1

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!

Sascha Kaestle
  • 1,203
  • 11
  • 15

2 Answers2

1

It is matter of coding style. With Ruby 2.0, you can also do this, which I may like better:

value = array[:first].to_h[:second].to_h[:four]

If you do not want to type to_h each time, you can define a method:

class Hash
  def safe_fetch k; self[k].to_h end
end
value = array.safe_fetch(:first).safe_fetch(:second)[:four]
sawa
  • 160,959
  • 41
  • 265
  • 366
  • Any idea how to define and use the `safe_fetch` method inside a Rails 5 application? – W.M. Sep 02 '17 at 21:09
-2

I will prefer inline rescue, as it is more Rubyistic.

array = {first: {second: {one: 1, two: 2, three: 3 }}}
value = array[:first][:second][:four] rescue nil # => nil
value = array[:first][:second][:two] rescue nil # => 2 
Arup Rakshit
  • 113,563
  • 27
  • 250
  • 306