Control contents of an array sample












1















I have a collection of books. In my view I want to show a random sample of 5 books from the top 10 bestselling books in my DB. However, I only want a maximum of ONE non-fiction title (book.genre) showing in that sample. It's ok if no non-fiction books are sampled.



Controller:



def index 
@top_selling_books = Book.all.order('units_sold DESC').first(10).sample(5)
end


View:



<% @top_selling_books.each.with_index(1) do |book, index| %>
<div>
<%= render "books/top_sellers", book: book, index: index %>
</div>
<% end %>









share|improve this question


















  • 1





    What happens if 7 of the top 10 books are non-fiction? Also to satisfy this requirement you are not truly sampling and should probably partition the dataset

    – engineersmnky
    Nov 14 '18 at 17:40






  • 1





    These requirements don't really make sense for the above mentioned edge case. I would suggest changing them to something like: "Show one of the top 3 non-fiction books, and 4 of the top 10 fiction books". Or maybe some other variation like: "Show one the top 10 overall books that's non-fiction (if it exists), and 4-5 of the top 10 fiction books (but not necessarily top 10 overall books), depending on whether that first book was found"

    – Tom Lord
    Nov 14 '18 at 17:55








  • 1





    ...In which case, you could just perform two queries and merge the result. Nothing too fancy.

    – Tom Lord
    Nov 14 '18 at 17:56
















1















I have a collection of books. In my view I want to show a random sample of 5 books from the top 10 bestselling books in my DB. However, I only want a maximum of ONE non-fiction title (book.genre) showing in that sample. It's ok if no non-fiction books are sampled.



Controller:



def index 
@top_selling_books = Book.all.order('units_sold DESC').first(10).sample(5)
end


View:



<% @top_selling_books.each.with_index(1) do |book, index| %>
<div>
<%= render "books/top_sellers", book: book, index: index %>
</div>
<% end %>









share|improve this question


















  • 1





    What happens if 7 of the top 10 books are non-fiction? Also to satisfy this requirement you are not truly sampling and should probably partition the dataset

    – engineersmnky
    Nov 14 '18 at 17:40






  • 1





    These requirements don't really make sense for the above mentioned edge case. I would suggest changing them to something like: "Show one of the top 3 non-fiction books, and 4 of the top 10 fiction books". Or maybe some other variation like: "Show one the top 10 overall books that's non-fiction (if it exists), and 4-5 of the top 10 fiction books (but not necessarily top 10 overall books), depending on whether that first book was found"

    – Tom Lord
    Nov 14 '18 at 17:55








  • 1





    ...In which case, you could just perform two queries and merge the result. Nothing too fancy.

    – Tom Lord
    Nov 14 '18 at 17:56














1












1








1








I have a collection of books. In my view I want to show a random sample of 5 books from the top 10 bestselling books in my DB. However, I only want a maximum of ONE non-fiction title (book.genre) showing in that sample. It's ok if no non-fiction books are sampled.



Controller:



def index 
@top_selling_books = Book.all.order('units_sold DESC').first(10).sample(5)
end


View:



<% @top_selling_books.each.with_index(1) do |book, index| %>
<div>
<%= render "books/top_sellers", book: book, index: index %>
</div>
<% end %>









share|improve this question














I have a collection of books. In my view I want to show a random sample of 5 books from the top 10 bestselling books in my DB. However, I only want a maximum of ONE non-fiction title (book.genre) showing in that sample. It's ok if no non-fiction books are sampled.



Controller:



def index 
@top_selling_books = Book.all.order('units_sold DESC').first(10).sample(5)
end


View:



<% @top_selling_books.each.with_index(1) do |book, index| %>
<div>
<%= render "books/top_sellers", book: book, index: index %>
</div>
<% end %>






ruby-on-rails ruby






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 17:28









B BB B

246138




246138








  • 1





    What happens if 7 of the top 10 books are non-fiction? Also to satisfy this requirement you are not truly sampling and should probably partition the dataset

    – engineersmnky
    Nov 14 '18 at 17:40






  • 1





    These requirements don't really make sense for the above mentioned edge case. I would suggest changing them to something like: "Show one of the top 3 non-fiction books, and 4 of the top 10 fiction books". Or maybe some other variation like: "Show one the top 10 overall books that's non-fiction (if it exists), and 4-5 of the top 10 fiction books (but not necessarily top 10 overall books), depending on whether that first book was found"

    – Tom Lord
    Nov 14 '18 at 17:55








  • 1





    ...In which case, you could just perform two queries and merge the result. Nothing too fancy.

    – Tom Lord
    Nov 14 '18 at 17:56














  • 1





    What happens if 7 of the top 10 books are non-fiction? Also to satisfy this requirement you are not truly sampling and should probably partition the dataset

    – engineersmnky
    Nov 14 '18 at 17:40






  • 1





    These requirements don't really make sense for the above mentioned edge case. I would suggest changing them to something like: "Show one of the top 3 non-fiction books, and 4 of the top 10 fiction books". Or maybe some other variation like: "Show one the top 10 overall books that's non-fiction (if it exists), and 4-5 of the top 10 fiction books (but not necessarily top 10 overall books), depending on whether that first book was found"

    – Tom Lord
    Nov 14 '18 at 17:55








  • 1





    ...In which case, you could just perform two queries and merge the result. Nothing too fancy.

    – Tom Lord
    Nov 14 '18 at 17:56








1




1





What happens if 7 of the top 10 books are non-fiction? Also to satisfy this requirement you are not truly sampling and should probably partition the dataset

– engineersmnky
Nov 14 '18 at 17:40





What happens if 7 of the top 10 books are non-fiction? Also to satisfy this requirement you are not truly sampling and should probably partition the dataset

– engineersmnky
Nov 14 '18 at 17:40




1




1





These requirements don't really make sense for the above mentioned edge case. I would suggest changing them to something like: "Show one of the top 3 non-fiction books, and 4 of the top 10 fiction books". Or maybe some other variation like: "Show one the top 10 overall books that's non-fiction (if it exists), and 4-5 of the top 10 fiction books (but not necessarily top 10 overall books), depending on whether that first book was found"

– Tom Lord
Nov 14 '18 at 17:55







These requirements don't really make sense for the above mentioned edge case. I would suggest changing them to something like: "Show one of the top 3 non-fiction books, and 4 of the top 10 fiction books". Or maybe some other variation like: "Show one the top 10 overall books that's non-fiction (if it exists), and 4-5 of the top 10 fiction books (but not necessarily top 10 overall books), depending on whether that first book was found"

– Tom Lord
Nov 14 '18 at 17:55






1




1





...In which case, you could just perform two queries and merge the result. Nothing too fancy.

– Tom Lord
Nov 14 '18 at 17:56





...In which case, you could just perform two queries and merge the result. Nothing too fancy.

– Tom Lord
Nov 14 '18 at 17:56












1 Answer
1






active

oldest

votes


















1














If you want to do complicated results, sometimes it's best not to do it all in one query. It can be much harder to maintain than simple logic. However, there is definitely a balance to maintainability, scalability, and performance.



I would suggest doing something like this:



def top_books(limited_genres: )
non_limited_books = Book.where.not(genre: limited_genres).order('units_sold DESC').first(10).sample(5)
limited_books = Book.where(genre: limited_genres).order('units_sold DESC').first(5).sample(1) # rename to limited_book if sample is kept to 1
(top_books + limited_books).sort_by(:units_sold)[0..5]
end

@top_selling_books = top_books(limited_genres: ['non-fiction'])


This is non tested code. It's just to give you an idea on how to accomplish your goals.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305735%2fcontrol-contents-of-an-array-sample%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you want to do complicated results, sometimes it's best not to do it all in one query. It can be much harder to maintain than simple logic. However, there is definitely a balance to maintainability, scalability, and performance.



    I would suggest doing something like this:



    def top_books(limited_genres: )
    non_limited_books = Book.where.not(genre: limited_genres).order('units_sold DESC').first(10).sample(5)
    limited_books = Book.where(genre: limited_genres).order('units_sold DESC').first(5).sample(1) # rename to limited_book if sample is kept to 1
    (top_books + limited_books).sort_by(:units_sold)[0..5]
    end

    @top_selling_books = top_books(limited_genres: ['non-fiction'])


    This is non tested code. It's just to give you an idea on how to accomplish your goals.






    share|improve this answer




























      1














      If you want to do complicated results, sometimes it's best not to do it all in one query. It can be much harder to maintain than simple logic. However, there is definitely a balance to maintainability, scalability, and performance.



      I would suggest doing something like this:



      def top_books(limited_genres: )
      non_limited_books = Book.where.not(genre: limited_genres).order('units_sold DESC').first(10).sample(5)
      limited_books = Book.where(genre: limited_genres).order('units_sold DESC').first(5).sample(1) # rename to limited_book if sample is kept to 1
      (top_books + limited_books).sort_by(:units_sold)[0..5]
      end

      @top_selling_books = top_books(limited_genres: ['non-fiction'])


      This is non tested code. It's just to give you an idea on how to accomplish your goals.






      share|improve this answer


























        1












        1








        1







        If you want to do complicated results, sometimes it's best not to do it all in one query. It can be much harder to maintain than simple logic. However, there is definitely a balance to maintainability, scalability, and performance.



        I would suggest doing something like this:



        def top_books(limited_genres: )
        non_limited_books = Book.where.not(genre: limited_genres).order('units_sold DESC').first(10).sample(5)
        limited_books = Book.where(genre: limited_genres).order('units_sold DESC').first(5).sample(1) # rename to limited_book if sample is kept to 1
        (top_books + limited_books).sort_by(:units_sold)[0..5]
        end

        @top_selling_books = top_books(limited_genres: ['non-fiction'])


        This is non tested code. It's just to give you an idea on how to accomplish your goals.






        share|improve this answer













        If you want to do complicated results, sometimes it's best not to do it all in one query. It can be much harder to maintain than simple logic. However, there is definitely a balance to maintainability, scalability, and performance.



        I would suggest doing something like this:



        def top_books(limited_genres: )
        non_limited_books = Book.where.not(genre: limited_genres).order('units_sold DESC').first(10).sample(5)
        limited_books = Book.where(genre: limited_genres).order('units_sold DESC').first(5).sample(1) # rename to limited_book if sample is kept to 1
        (top_books + limited_books).sort_by(:units_sold)[0..5]
        end

        @top_selling_books = top_books(limited_genres: ['non-fiction'])


        This is non tested code. It's just to give you an idea on how to accomplish your goals.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 18:54









        DbzDbz

        2,00142743




        2,00142743
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305735%2fcontrol-contents-of-an-array-sample%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python