title: How to sort the items in an array to match the order that it appears in another array
body: <p>I want to grab the ratings from movies in the database and return an array of unique ratings, sorted in the following order:</p>
  
  <pre><code>G PG PG-13 R NC-17
  </code></pre>
  
  <p>A plain <code>Array#sort</code> wasn't enough:</p>
  
  <pre><code>["PG-13", "PG", "NC-17", "G", "R"].sort
  # =&gt; ["G", "NC-17", "PG", "PG-13", "R"]
  </code></pre>
  
  <p>The following code gives me what I want, but seems like there's a better way to write it not having to use <code>delete</code> and <code>&lt;&lt;</code>. Any ideas would be appreciated.</p>
  
  <pre><code>class Movie &lt; ActiveRecord::Base
    def self.all_ratings
      allRatings = []
      Movie.all.each do |movie|
        unless allRatings.include?(movie.rating)
          allRatings &lt;&lt; movie.rating
        end
      end
      if allRatings.include?("NC-17")
        allRatings.sort!
        allRatings.delete("NC-17")
        allRatings &lt;&lt; "NC-17"
        return allRatings
      else
        return allRatings.sort
      end
    end
  end
  </code></pre>
  
  <hr>
  
  <p>UPDATE:
  Using Sergio's tip, I was able to refactor the code. If anyone has some other ideas, I'd appreciate the feedback.</p>
  
  <pre><code>class Movie &lt; ActiveRecord::Base
  
    def self.all_ratings
      allRatings = []
      Movie.all.each do |movie|
        unless allRatings.include?(movie.rating)
          allRatings &lt;&lt; movie.rating
        end
      end
      allRatings.sort_by! {|t| t == 'NC-17' ? 'ZZZ' : t}
    end
  end
  </code></pre>
  
  <hr>
  
  <p>UPDATE:
  Using ByScripts tip, this code works well and is very concise. I had to upgrade from Rails 3.1.0 to Rails 3.2.8 to get the <code>pluck</code> method. Looks like it was introduced in 3.2.1.</p>
  
  <p>I also had to add <code>.sort</code> to get the desired output.</p>
  
  <pre><code>class Movie &lt; ActiveRecord::Base
  
    def self.all_ratings
      all_ratings = Movie.pluck(:rating).uniq.sort# don't retrieve unnecessary datas
      all_ratings &lt;&lt; all_ratings.delete('NC-17') # directly inject NC-17 at the end if exists
      all_ratings.compact # remove nil values
    end
  
  end
  </code></pre>