简体   繁体   中英

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.

<% 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 %>

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

the above will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM