简体   繁体   中英

How to iterate over an array of arrays in Ruby

I have an array of arrays that contains details of three tests. This is the array:

test_arr = [
  [‘unit test 1’, ‘physics’, ‘25’],
  [‘unit test 2’, ‘chemistry’, ‘30’],
  [‘final test’, ‘math’, ‘50’]
]

I want to iterate over this array three times (because there are only three tests whose data is contained in the array) to get a hash in an array containing only the subject and marks.

I do the iteration as follows:

test_arr.each do |ta|
  all_test_details << { subject: ta[1], marks: ta[2] }
end

I want all_test_details to read like this =>

[ { subject: ‘physics’, marks: 25 },
  { subject: ‘chemistry’, marks: 30 },
  { subject: ‘math’, marks: 50 } ]

But when I run the code, what I get is all_test_details repeated ten times. I'm unable to figure out why.

How do I get the names and marks of the test in a single array containing a hash?

Make use of map :

test_arr.map { |data| { subject: data[1], marks: data[2] } }

#=> [{:subject=>"physics",   :marks=>"25"},
#=>  {:subject=>"chemistry", :marks=>"30"},
#=>  {:subject=>"math",      :marks=>"50"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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