user984621
user984621

Reputation: 48443

Ruby - loop through array

In a form I have a list of products from database and every product has these items in the form:

= text_field_tag 'item['+product.id.to_s+'][]'
= text_field_tag 'item_value1['+product.id.to_s+'][]'
= text_field_tag 'item_value2['+product.id.to_s+'][]'

I am trying to loop over the array and get all those (item, item_value1, item_value2) this way:

params[:item].each_with_index do |val, index|
  puts "#{val[0]} => #{val[1]}"
end

and the output is like:

191359 => [""]
191361 => [""]
191360 => ["15"]
191212 => [""]
191210 => ["9"]
248974 => [""]
191209 => [""]
190920 => [""]
190919 => [""]
190921 => [""]

But, how to get all data for the respective products? Something like

puts "item: #{item}, item_value1: #{item_value1}, item_value2: #{item_value2}"

Upvotes: 0

Views: 1305

Answers (1)

Rubyman
Rubyman

Reputation: 874

There are three parameters here item, item_value1 and item_value2. Iterating over item will give you values from parameter items only and not from intem_value1 and item_value2. If the indexes of these 3 parameters are relative, then you can play with index as in your code

params[:item].each_with_index do |val, index|
  puts "#{params[:item_value1][index]} => #{params[:item_value1][index]}"
end

Upvotes: 2

Related Questions