0

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? I am still new to Ruby, please help. Thanks

Update Those number (1415498778636 and 1415498795509) is always changing, so the loop must be able to handle any different kind of numbers

1
  • In future, please simplify your example as much as possible. Here, for example, there are many key-value pairs that could be removed without making the example less meaningful. Also, shortening names makes it more readable. Commented Nov 9, 2014 at 3:17

3 Answers 3

1
params['student_work']['work_experiences_attributes'].values.each do |hash|
  hash.each do |key, value|
    # ...
  end
end
Sign up to request clarification or add additional context in comments.

Comments

0

Actually as student_work[work_experiences_attributes] is a Hash, so you can just use each method.

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

Comments

0

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

1 Comment

Ok. The width is fixed?

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.