Abhi Ram A
Abhi Ram A

Reputation: 305

How to get unique elements through array and group them in ruby on rails

i have issue. This below code is the views code of ruby in rails

<table >
<tr>
    <th>Url</th>
    <th>Tags</th>
</tr>   
 <% @array_bookmark = @bookmark.class == Array ? @bookmark : [@bookmark] %> 
 <% Array(@bookmark).each do |book| %>
 <tr>
 <td><%= book.url %></td>
 <td><%= book.tags %></td>
 </tr>
 <% end %>
 </table>

This yields something like :

  Url                   Tags
 www.mrabhiram.tumblr.com   abhi
 www.mrabhiram.tumblr.com   blog
 google.com                 google
 google.com                 blog

But, i want to get it as

  Url                   Tags
 www.mrabhiram.tumblr.com   abhi,blog
 google.com                 google,blog

Can anyone provide me the solution? It should be generic enough to iterate over the array.

Thank you in advance.

Upvotes: 0

Views: 1673

Answers (3)

Pavel S
Pavel S

Reputation: 1543

Use group_by statement

upd

 <% Array(@bookmark).group_by(&:url).each do |url, books| %>
 <tr>
 <td><%= url %></td>
 <td><%= books.map(&:tags).flatten.join(',') %></td>
 </tr>

Upvotes: 1

Valery Kvon
Valery Kvon

Reputation: 4496

<% Array(@bookmark).group_by {|b| b.url}.each do |url, books| %>
  <tr>
    <td><%= url %></td>
    <td><%= books.map {|b| b.tags}.flatten.uniq.join(" ") %></td>
  </tr>
<% end %>

Upvotes: 2

VenkatK
VenkatK

Reputation: 1305

<% Array(@bookmark).uniq.each do |book| %>
 <tr>
 <td><%= book.url %></td>
   <td><%= book.tags %></td>
 </tr>
<% end %>

the above will work.

Upvotes: 0

Related Questions