簡體   English   中英

將哈希值放入數組RUBY

[英]Put hash values into array RUBY

我正在使用ruby 1.9.3,並從API GET請求接收以下哈希:

puts api_response

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

如何將每個ID放入自己的數組中? 就像是:

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

哈希值之間沒有逗號分隔,我認為這就是讓我失望的原因。

嘗試這個:

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

有關更多文檔,請查看Enumerable#map

編輯:

哈希沒有被逗號分隔的原因是因為Kernel#puts如何在數組上工作。 嘗試puts [1,2,3]並自己看看:每個元素都按自己的行顯示,沒有逗號。

api_response是一個哈希數組,因此我在上面的答案將每個哈希從數組中取出,並提取"id"字段。

resp_str = <<EOS
{"id"=>"5172901-01", "firstName"=>"a", "lastName"=>"b", "email"=>"test@test.com", "gender"=>"U", "dateOfBirth"=>"1983-08-05"}
{"id"=>"2072902-01", "firstName"=>"c", "lastName"=>"d", "email"=>"test@test.com", "gender"=>"U", "dateOfBirth"=>"1955-04-01"}
{"id"=>"1072903-01", "firstName"=>"e", "lastName"=>"f", "email"=>"test@test.com", "gender"=>"M", "dateOfBirth"=>"1987-12-31"}
{"id"=>"2072817-04", "firstName"=>"g", "lastName"=>"h", "email"=>"test@test.com", "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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM