← Back to Upcase

API returning hash or array, how to handle?


(Nate Eckerson) #1

I’m working with the Amazon MWS API. I’ve discovered that the API returns a single hash, or an array of hashes depending on the number of reports generated.

I want to iterate over the hash/hashes and pull out values. I’ve written the code below. Is this the best “ruby” way to handle the problem?

def handle_response(response)
  if response.is_a?(Hash)
    [response]
  else
    response
  end
end

Then I do something like…

responses = handle_response(api_response)

responses.each do |response|
  some_array << response[:some_key]
end

I could handle this better with responses.map, but you get the general idea.