0

I have an array of arrays, and when I loop through the array the only one displayed is the last array.

Here is the code that loops through the arrays;

@events.each do |event|
  def get_sig_class_id(sig_id)
    IpsSignature.where('sig_id =?', sig_id).first.sig_class_id
  end
  sig_id = get_sig_class_id(event.signature)
  event_class_data.push(sig_id)
  @event_class_array = Array.new(event_class_data.group_by {|x| x}.map {|k,v| [k,v.count]})
  @event_class_array.each do |x|
    @event_class = x
  end
end

If I display @event_class_array in my view I get this [[1, 54], [30, 1], [2, 1]]

If I display @event_class in the view I only get [2, 1]

I'm looking to get [1, 54], [30, 1], [2, 1] with @event_class (single arrays, not an array of arrays as in @event_class_array, and not just the last one).

My displaying in the view is simply to see what data I'm getting returned, this will eventually end up in a Highcharts pie chart.

Here are my views, nothing much to see here..

<%= @event_class_array %>

and

<%= @event_class %>
5
  • 1
    That's hard to read. Why do you define a method in your loop? Also, you're setting event_class instead of appending to it. Commented Jun 22, 2014 at 22:52
  • What do you mean setting? Commented Jun 22, 2014 at 22:56
  • You're setting the value to x instead of appending to an array. Also, canonical Ruby would use map/collect instead of appending inside an each loop. Commented Jun 22, 2014 at 22:58
  • And I don't see the point of defining that method inside a loop. Commented Jun 22, 2014 at 22:59
  • Thanks for clearing this up, I'll move the methods. I'm new to development and I was getting undefined method errors, so thats how I got it working. Commented Jun 22, 2014 at 23:10

2 Answers 2

2
  @event_class_array.each do |x|
    @event_class = x
  end

this code means that for each array, @event_class is rewrited with the x. So only the last one is stored there.

If you want to insert all arrays you should do

  @event_class = [] 
  @event_class_array.each do |x|
    @event_class << x
  end
Sign up to request clarification or add additional context in comments.

Comments

0
@event_class_array.each do |x|
    @event_class = x
end

You're overwriting @event_class every time that line fires. Change it to something like

@event_class_array.each do |x|
    @event_class += x
end

And you should be good.

Comments

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.