0

I am using ruby 1.9.3 and am receiving the following hash back from an API GET request:

puts api_response

{"id"=>"5172901-01", "firstName"=>"a", "lastName"=>"b", "email"=>"[email protected]", "gender"=>"U", "dateOfBirth"=>"1983-08-05"}
{"id"=>"2072902-01", "firstName"=>"c", "lastName"=>"d", "email"=>"[email protected]", "gender"=>"U", "dateOfBirth"=>"1955-04-01"}
{"id"=>"1072903-01", "firstName"=>"e", "lastName"=>"f", "email"=>"[email protected]", "gender"=>"M", "dateOfBirth"=>"1987-12-31"}
{"id"=>"2072817-04", "firstName"=>"g", "lastName"=>"h", "email"=>"[email protected]", "gender"=>"U", "dateOfBirth"=>"1985-04-07"}

How can i put each id into it's own array? Something like:

api_response[:id].each do |x|
  api_response_array << x
end

The hashes aren't seperated by commas and I think that is what's throwing me off.

1
  • 2
    What is api_response? is it a Hash or a String? Commented Aug 20, 2013 at 18:01

2 Answers 2

4

try this:

api_response.map { |x| x["id"] }

For more documentation, check out Enumerable#map

EDIT:

The reason the hashes aren't separated by commas is because of how Kernel#puts works on an array. Try puts [1,2,3] and see for yourself: each element goes on its own line, without commas.

api_response is an array of hashes, so my answer above takes each hash out of the array, and extracts the "id" field.

Sign up to request clarification or add additional context in comments.

Comments

1
resp_str = <<EOS
{"id"=>"5172901-01", "firstName"=>"a", "lastName"=>"b", "email"=>"[email protected]", "gender"=>"U", "dateOfBirth"=>"1983-08-05"}
{"id"=>"2072902-01", "firstName"=>"c", "lastName"=>"d", "email"=>"[email protected]", "gender"=>"U", "dateOfBirth"=>"1955-04-01"}
{"id"=>"1072903-01", "firstName"=>"e", "lastName"=>"f", "email"=>"[email protected]", "gender"=>"M", "dateOfBirth"=>"1987-12-31"}
{"id"=>"2072817-04", "firstName"=>"g", "lastName"=>"h", "email"=>"[email protected]", "gender"=>"U", "dateOfBirth"=>"1985-04-07"}
EOS


resp_array = resp_str.lines.map {|line| eval(line) }
id_array = resp_array.map {|h| h['id']}

puts id_array.inspect

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.