Delete duplicate records from a 2 dimensional array in rails

288 views
Skip to first unread message

pradeep...@gmail.com

unread,
Sep 6, 2013, 10:47:46 AM9/6/13
to rubyonra...@googlegroups.com
Hello,

I am trying to insert elements into an array like this...

@mem = []
@tran = Transport.find_all_by_month_and_vehicle(date,vehicle)
tran.each do |t|
  @mem << [Student.find_by_id(t.mem_id), t.transport_date, vehicle.no] if t.mem_type=="Student"
  @mem << [Employee.find_by_id(t.mem_id), t.transport_date, vehicle.no] if t.mem_type=="Employee"
end

And in the view page I am looping and displaying it as

@mem.each do |m| <tr> <td><%= link_to m[0].first_name} %></td> <td > <%= m[0].age %></td> <td id="date"> m[1] </td> <td id="vehicle"> m[2] </td> </tr> <%end%>

But I am getting duplicate entries in the table... So I neeed to remove duplicates and display only unique values.. I tries doing

@mem << [Student.find_by_id(t.mem_id), t.transport_date, vehicle.no].uniq! if t.mem_type=="Student".. But it is not working.. Please help

Crispin Schäffler

unread,
Sep 9, 2013, 4:17:38 AM9/9/13
to rubyonra...@googlegroups.com
@tran = Transport.where( date: date, vehicle: vehicle)
@mem = @tran.members

Iterate in view

@mem.each do |mem|
mem.name
mem.vehicle

Should work if you have the relations set up. You should go read one or two tutorials about relations and how to set them up.

Max

unread,
Sep 9, 2013, 8:33:39 AM9/9/13
to rubyonra...@googlegroups.com
if you really need to do some processing that gets you an array with duplicate entries and then clean the array at the end of it all.  try doing something like

@mem = @mem.uniq

you can probably do @mem.uniq!  but i've had some cases where that didn't get me the results i wanted.

Joel Pearson

unread,
Sep 9, 2013, 5:29:29 PM9/9/13
to rubyonra...@googlegroups.com
uniq can take a block as well if you wanted to unique similar arrays on
a specific element:

@mem.uniq { |mem| mem[1] }

Or even on multiple criteria:

@mem.uniq { |mem| [ mem[1], mem[2] ] }

--
Posted via http://www.ruby-forum.com/.

Sergei Barilov

unread,
Nov 20, 2013, 12:09:36 AM11/20/13
to rubyonra...@googlegroups.com
Joel Pearson wrote in post #1121051:
> uniq can take a block as well if you wanted to unique similar arrays on
> a specific element:
>
> @mem.uniq { |mem| mem[1] }
>
> Or even on multiple criteria:
>
> @mem.uniq { |mem| [ mem[1], mem[2] ] }


This was very helpful

Thank you
Reply all
Reply to author
Forward
0 new messages