Matthias74
Matthias74

Reputation: 3

Array iteration in rails controller: it only puts the last value

I have to iterate on array in my rails controller but it only returns the last value of it:

array = ["a", "b", "c"]

 array.each do |arr|
   @arry = arr
 end

@arry gives me "c" but I want it to give me a b c

So, when I add a API method in the each iteration, it only gives me a result for the "c" value but I want a result for all of them.

FYI: when I iterate this array in my view, everything works

Upvotes: 0

Views: 337

Answers (2)

Argonus
Argonus

Reputation: 1035

array.each do |el|
  @arr = el
end

Every loop you are saving el as @arr (overriding previous value)so after full each you have last el. You can do it like this if you want to do something with each element.

@arr = array.map { |el| el }

or just

@arr = array

Upvotes: 1

Alex Kojin
Alex Kojin

Reputation: 5214

Use map enumerator:

@arry = array.map { |arr| arr }

https://ruby-doc.org/core-2.2.0/Array.html#method-i-map

Upvotes: 0

Related Questions