简体   繁体   English

Ruby on Rails中的每个循环

[英]Each loop in Ruby on Rails

So I have this following request: 因此,我有以下要求:

{"utf8"=>"✓",
 "student_work"=>{"work_experiences_attributes"=>{"1415498778636"=>{"company_name"=>"Company1",
 "start_year"=>"2014",
 "end_year"=>"2014",
 "job_title"=>"Title1",
 "job_description"=>"test1"},
 "1415498795509"=>{"company_name"=>"Company2",
 "start_year"=>"2014",
 "end_year"=>"2014",
 "job_title"=>"Title2",
 "job_description"=>"Test2"}}},
 "commit"=>"Next"}

or to make it easier: 或使其更容易:

student_work[work_experiences_attributes][1415498778636][company_name]:Company1
student_work[work_experiences_attributes][1415498778636][start_year]:1
student_work[work_experiences_attributes][1415498778636][start_year]:2014
student_work[work_experiences_attributes][1415498778636][end_year]:2
student_work[work_experiences_attributes][1415498778636][end_year]:2014
student_work[work_experiences_attributes][1415498778636][job_title]:Title1
student_work[work_experiences_attributes][1415498778636][job_description]:test1
student_work[work_experiences_attributes][1415498795509][company_name]:Company2
student_work[work_experiences_attributes][1415498795509][start_year]:3
student_work[work_experiences_attributes][1415498795509][start_year]:2014
student_work[work_experiences_attributes][1415498795509][end_year]:4
student_work[work_experiences_attributes][1415498795509][end_year]:2014
student_work[work_experiences_attributes][1415498795509][job_title]:Title2
student_work[work_experiences_attributes][1415498795509][job_description]:Test2

How do I access each values using the each loop in Ruby? 如何使用Ruby中的each循环访问每个值? I am still new to Ruby, please help. 我还是Ruby的新手,请帮助。 Thanks 谢谢

Update Those number (1415498778636 and 1415498795509) is always changing, so the loop must be able to handle any different kind of numbers 更新那些数字(1415498778636和1415498795509)始终在变化,因此循环必须能够处理任何其他类型的数字

params['student_work']['work_experiences_attributes'].values.each do |hash|
  hash.each do |key, value|
    # ...
  end
end

Actually as student_work[work_experiences_attributes] is a Hash, so you can just use each method. 实际上,由于student_work[work_experiences_attributes]是一个哈希,因此您可以使用each方法。

http://www.ruby-doc.org/core-2.1.4/Hash.html#method-i-each http://www.ruby-doc.org/core-2.1.4/Hash.html#method-i-each

You mean response instead request right? 您是说回应而是要求对吗? You could do: 您可以这样做:

attr=params[:student_work].keys.each do |key|
    key.to_i > 0
end[0] 
params[:student_work][attr].each do |key, value|
# do something
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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