Why does this Ruby statement throw an exception? (Arrays/Bools)
I'm not a Ruby guy, I just play one on television. I have to modify someone's old Cron job to pull down some JSON and convert it into objects.
Here's the code
raw_json = Net::HTTP.get(URI.parse("url removed to protect the innocent"))
tags = ActiveSupport::JSON.decode(raw_json开发者_C百科)
puts tags.count
tags.count will accurately trace as 5, but THAT LINE immediately causes a crash as follows:
5 #the accurate count!
rake aborted!
undefined method `count' for false:FalseClass
What is the dealio?
What is the contents of raw_json
? What appears to be happening is that ActiveSupport::JSON#decode
is returning false (hence undefined method 'count' for false:FalseClass
). I think JSON#decode
only returns false when given an empty string, which would mean HTTP#get
is returning an empty string. Check on raw_json
and see if it contains what you expect.
so I have no idea what is going on here, but JSON.decode should give you a hash, which doesn't have a count method. It does have a size method though
tags.size
if that doesn't work, try doing p tags, or puts tags.class.name to try and figure out what you are working with
Apparently tags is false , which may mean that your Net::HTTP.get failed (I guess your URL is wrong). Try to print tags to see what it is. (I guess anyway, that you should use a valid URI)
The problem is that:
>> ActiveSupport::JSON::decode("")
=> false
>> ActiveSupport::JSON::decode("false")
=> false
This is a very strange behavior.
精彩评论