I have the following:
sets = DataSet.all.group_by{ |data| [data.project_id, "-", data.thread_id].join(" ") }
<% sets.each do |range, datas| %>
<p><%= range %>:</p>
<% datas.each do |data| %>
<%=data%>
<p>Last Post<%= data.last.created_at %></p>
<% end %>
<% end %>
Problem is that I need an index. So i updated the above with:
<% sets.each_with_index do |range, datas, i| %>
<p><%= range %>:</p>
<% datas.each do |data| %>
<%= i %>
<%=data%>
<p>Last Post<%= data.last.created_at %></p>
<% end %>
<% end %>
That then breaks, with the error: undefined method `last' for 0:Fixnum
Ideas? thank you
The issue you observe is because of the way parameters are assigned to the block. In your second example, you will observe that
rangecontains an array containing a singlerangeand the matchingdatas, thedatasvariable contains the index andiis alwaysnil.This is because ruby "unsplats" arrays if it is the only parameter to the block. If you have more than one type (in this case an array and an integer), you must hint ruby on what it should do. The simplest way is to use parentheses.
That way, ruby will know what you mean and split the array up into
rangeanddatas. This is actually a feature of ruby's assignment operator in conjunction with the comma operator. It works like this