Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "undefined method `[]' for nil:NilClass" when working with nested Ruby hashes?

Tags:

json

ruby

hash

I'm working with the Steam Storefront API - http://store.steampowered.com/api/appdetails/?appids=240

I've parsed the JSON into a hash.

When I try to select any hash value nested inside of "data" I receive an "undefined method `[]' for nil:NilClass" error.

I can puts the whole lot with res["240"]["data"] which shows me all of the keys and values. All of which seem to look fine.

However when I try to go one branch further it throws nil.

res["240"]["data"]["type"]

Using .key also throws up an error.

res["240"]["data"].key

My quest to find an answer has mainly found suggestions of searching for the key & values, however I know the direct route to the data so I'd like to go this route if possible.

Thanks.

like image 507
grim Avatar asked Jul 18 '26 10:07

grim


2 Answers

If you're on ruby 2.3, you may use dig, as suggested by @sawa.

http://docs.ruby-lang.org/en/2.3.0/Hash.html#method-i-dig

However, if you are not on ruby 2.3, then things get a bit trickier.

The simplest approach is to implement your own version of dig:

class Hash
  def dig(*path)
    path.inject(self) do |h, k|
      h.respond_to?(:keys) ? h[k] : nil
    end
  end
end

Then you can just res.dig("240", "data", "type")

like image 179
paradox460 Avatar answered Jul 21 '26 01:07

paradox460


You can use dig in combination with the safe navigation operator, like:

res&.dig("240", "data", "type")

If res is nil (or more accurately isn't "digable") then it will return nil instead of raising.

like image 36
cdmo Avatar answered Jul 21 '26 03:07

cdmo