5

I'm trying to analyze tweets off of Twitter and one of the things I would like to include is the location. Unfortunately, some of the values are nil and I keep getting the error

undefined method `[]' for nil:NilClass (NoMethodError)

I would like to just run a check to see if the value is nil or not but I can't get anything to work.

The input would look like this if it is nil

tweet = {"metadata"=> {"geo"=>nil}}

and this if it has value

tweet = {"metadata"=> {"geo"=>{"coordinates"=>[0,1]}}

This is what I've tried

if "#{tweet['metadata']['geo']}".nil? == true
  puts("nil")
else
  puts("#{tweet['metadata']['geo']['coordinates']}"
end

What I've noticed is that it just checks to see if geo is empty because it outputs "nil" if I change the if statement to equal false. I'm not sure how else to check

nickg
  • 137
  • 1
  • 2
  • 12

4 Answers4

3

I think the problem may be that you're interpolating the hash in the string, which is converting the nil into an empty string, which is not actually nil.

Try:

if tweet['metadata']['geo'].nil?
  puts("nil")
else
  puts("#{tweet['metadata']['geo']['coordinates']}")
end
Rebitzele
  • 3,252
  • 1
  • 20
  • 21
3

Using fetch on hash is a better way to Handle this type of problems. The below link to another answer shows how elegantly and beautifully this is handled. Ruby - Access multidimensional hash and avoid access nil object

Community
  • 1
  • 1
Raja
  • 181
  • 1
  • 3
2

Use present? which checks for nil and blank as well. Check with following code.

if tweet['metadata']['geo'].present?
  puts("nil")
else
  puts("#{tweet['metadata']['geo']['coordinates']}")
end
Data Don
  • 338
  • 2
  • 11
0

In case anyone stumbles upon this, nowadays I'd suggest using dig with safely returns nil if keys are not present.

tweet = { "metadata" => { "geo"=> { "coordinates" => [0, 1] } } }
tweet.dig("metadata", "geo", "coordinates")
=> [0, 1]

missing_tweet = { "metadata" => { "geo" => nil } }
missing_tweet.dig("metadata", "geo", "coordinates")
=> nil
abax
  • 727
  • 5
  • 9