Skipping empty element when looping through Array using Ruby
I am bei开发者_C百科ng returned an array with 10 different Amazon aws_objects. I want to loop through each of them and save them to my DB, but sometimes the Amazon API returns empty arrays. For example, the title method might work successfully, but the medium_image method might return nil, thus breaking the loop. I understand I need to use some conditional function here, I am just not sure how to do it in a way that works every time. ( also would be nice if I could just skip the empty array, and continue to save data after).
items.each do |aws_object|
if aws_object.blank? == false
@amazonproduct = Amazonproduct.new
@amazonproduct.name = aws_object.item_attributes.title.to_s.gsub("&", "&")
@amazonproduct.asin = aws_object.asin.to_s
@amazonproduct.image_url = aws_object.medium_image.url.to_s
@amazonproduct.description = aws_object.item_attributes.feature.to_s
@amazonproduct.price = aws_object.item_attributes.list_price.formatted_price.to_s.gsub("$", "")
@amazonproduct.object_url = aws_object.item_links.item_link[0].url.to_s
@amazonproduct.save
end
end
I have tried using while, if, unless - having trouble coming up with the right combination.
Thank you for any help!
James
First, to skip the empty items in the array you could use:
items.compact.each do |aws_object|
The compact call will return the array with all nil entries removed. And if you have to test the attributes you can do something like this:
@amazonproduct.image_url = aws_object.medium_image.url.to_s unless aws_object.medium_image.nil?
You should check for two conditions in the loops... one is array.nil
or array.empty
If any of these evaluates to true, move on to next record...
精彩评论