Ruby Compare Attributes in Array of Objects
<p>I have an User model and a Concert model in my Ruby on Rails project. The User has an array containing all the concerts of his favorite bands, and the Concert model has the city and date attributes. </p>

<p>What I need to do is iterate through this array of concerts to see if they´re any concerts that are happening the same day in the same city.</p>

<p>Something like this: </p>

<pre><code>  @user_concerts = [concert1, concert2, concert3....]
</code></pre>

<p>I guess I'll have to loop over this array two times, but I'm a bit stuck with this.</p>

<p>The way my DB is made, I use the query below to get the IDs of the bands favorited by a user.</p>

<pre><code>bands_ids_array =  UsersBand.where(user_id: current_user.id, is_favorite: true).pluck(:band_id)
    @user_favorite_bands = [] 
    bands_ids_array.each do |id|
         @user_favorite_bands &lt;&lt; Band.find(id)
        end
</code></pre>

<p><code>UsersBand</code> is the relational DB between <code>User</code> and <code>Band</code> models. It contains <code>user_id</code>, <code>band_id</code> and a Boolean field <code>is_favorite</code>.</p>

<p>To get all the concerts I do the following currently:   </p>

<pre><code>@user_concerts = []
@user_favorite_bands.each do |band|
        band.concerts.each do |concert|
            @user_concerts.push(concert)
        end
    end
</code></pre>

<p>I´ve tried nesting two "each" loops, a while loop nested inside an "each" trying to compare all the concerts to see if they have the same city or date, but that didn´t work.</p>

<p>Edit: I did that and it worked for me:</p>

<pre><code>for i in (0..@user_concerts.length) do 
        for j in (i+1..@user_concerts.length-1) do
            if @user_concerts[i].city == @user_concerts[j].city &amp;&amp; @user_concerts[i].date == @user_concerts[j].date
                matches.push(@user_concerts[i])
                matches.push(@user_concerts[j])
            end
        end
</code></pre>

<p>Any help will be appreciated. Thanks a lot guys.</p>