开发者

Is there a Hash nil check for fetch?

I'm using the facebook graph-api and I'm fetching the checkin keys. Most places have this checkin key, but every once in a while I find a place with no checkins that does not have this key. Is there a way to check for nil and prevent the following code开发者_JAVA百科 from blowing up my very large rake?

graph.get_object(5811874893).fetch("checkins")
KeyError: key not found: "checkins"


x =  graph.get_object(x.place_id)["checkins"]

Based on feedback below I have the following error, with the same theme: nil checking. How would you handle this?

nil can't be coerced into Fixnum


Have you tried seeing if has_key? is available, or using graph.get_object(5811874893)["checkins"] rather than graph.get_object(5811874893).fetch("checkins")?

To return 0 if there isn't checkins, do

graph.get_object(5811874893).fetch("checkins") { 0 }

The block after fetch specifies what to do if "checkins" doesn't exist.


Why don't you just do

graph.get_object(5811874893)["checkins"]

If you access a hash using [], no error will be raised, and you'll get a nil value (as long as the hash doesn't set it to something else).


What you want is this:

graph.get_object(5811874893).fetch("checkins", 0)

fetch accepts a second optional param which represents the default value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜