Home > Mobile >  I have a table with a currency column and an array of currencies, I want to assign each instance of
I have a table with a currency column and an array of currencies, I want to assign each instance of

Time:12-29

So that each elements of the array gets assigned to each instance of the column chronologically

This is what I've tried:

currencies = [...]

i = 0
Country.all.each do |country|
  Country.update(currency: currencies[i])
  i = i   1
end

currencies.each do |currency|
  Country.all.each do |country|
    country.update(currency: currency)
  end
end

My expectation/desire is to get the first country column assigned with the value of the first array element, the second country column with the second element etc.

CodePudding user response:

Solved.

i = 0
Country.all.each do |country|
  country.update(currency: currencies[i])
  i  = 1
end

CodePudding user response:

You can make it simpler:

Country.all.each_with_index do |country, i|
  country.update(currency: currencies[i])
end

Any chance to use zip method:

Country.all.zip(currencies) do |country, currency|
  country.update(currency: currency)
end

Make it repeat:

Country.all.zip([:usd, :eur, :gbp].cycle) do |country, currency|
  country.update(currency: currency)
end
  • Related