简体   繁体   中英

How do I exclude data from an API call that have a value of nil in Ruby?

I'm trying to pull user data from the NationBuilder API to display on Google Maps. I need the latitude and longitude of these users, and if an address is given, NationBuilder will provide 'lat' and 'lng' values in the JSON hash. But some of the users in the database don't have lat and lng values, which makes me get an error when I ask for the lat and lng of each user.

In my API call, I want to be able to exclude people who have a lat and lng value of nil so they aren't even rendered to stop me from getting an error.

Here's what the call looks like currently:

users = client.call(:people_tags, :people, tag: 'mapped')["results"] users.map { |user| new(user) }

Please let me know if you need more information to answer this question.

You could reject users whose lat or long is nil :

users_with_location = users.reject { |user| user.lat.nil? || user.long.nil? }

Or reject in place (remove them from your users variable without making a copy):

users.reject! { |user| user.lat.nil? || user.long.nil? }

So your entire code would be something like:

users = client.call(:people_tags, :people, tag: 'mapped')["results"]
users.reject! { |user| user.lat.nil? || user.long.nil? }
users.map { |user| new(user) }

Take a look at select and compact methods.

For example to exclude simple nil -s use compact :

users.compact.map { |user| User.new(user) }

Or in a bit more idiomatic way:

users.compact.map(&User.method(:new))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM