How Yield statement in ruby works?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















Can someone please show how to correctly format this yield statement, and why my methodology for this yield statement is incorrect? When run, the compiler results in an "undefined method 'length' error. "Test" is the main class.



  def bubble_sort_by(array)
len = array.length - 1
while len > 0
for i in(1..len)
@left = array[i]
@right = array[i - 1]
yield
if @left - @right > 0
array[i - 1], array[i] = array[i], array[i - 1]
end
end
len -= 1
end
p array
end

Test.bubble_sort_by(%w[hi hello hey]) do |left, right|
left.length - right.length
end









share|improve this question

























  • If the block were { |a,b| a*b } and c = yield(2,3), a and b would be assigned values 2 and 3, respectively, so the block would return 6, which would be assigned to the variable c.

    – Cary Swoveland
    Nov 25 '18 at 0:34













  • Thank you for responding, Cary. @CarySwoveland how is " if yield(array[i-1], array[i]) > 1" not the same as the code written above for the if statement.

    – Lawleyenda
    Nov 25 '18 at 0:46













  • No, the body of the block (left.length - right.length) only has access to the variables directly passed to it by yield, not to any variables or methods that would be accessible within the method doing the yielding (bubble_sort_by).

    – Max
    Nov 25 '18 at 2:13


















0















Can someone please show how to correctly format this yield statement, and why my methodology for this yield statement is incorrect? When run, the compiler results in an "undefined method 'length' error. "Test" is the main class.



  def bubble_sort_by(array)
len = array.length - 1
while len > 0
for i in(1..len)
@left = array[i]
@right = array[i - 1]
yield
if @left - @right > 0
array[i - 1], array[i] = array[i], array[i - 1]
end
end
len -= 1
end
p array
end

Test.bubble_sort_by(%w[hi hello hey]) do |left, right|
left.length - right.length
end









share|improve this question

























  • If the block were { |a,b| a*b } and c = yield(2,3), a and b would be assigned values 2 and 3, respectively, so the block would return 6, which would be assigned to the variable c.

    – Cary Swoveland
    Nov 25 '18 at 0:34













  • Thank you for responding, Cary. @CarySwoveland how is " if yield(array[i-1], array[i]) > 1" not the same as the code written above for the if statement.

    – Lawleyenda
    Nov 25 '18 at 0:46













  • No, the body of the block (left.length - right.length) only has access to the variables directly passed to it by yield, not to any variables or methods that would be accessible within the method doing the yielding (bubble_sort_by).

    – Max
    Nov 25 '18 at 2:13














0












0








0








Can someone please show how to correctly format this yield statement, and why my methodology for this yield statement is incorrect? When run, the compiler results in an "undefined method 'length' error. "Test" is the main class.



  def bubble_sort_by(array)
len = array.length - 1
while len > 0
for i in(1..len)
@left = array[i]
@right = array[i - 1]
yield
if @left - @right > 0
array[i - 1], array[i] = array[i], array[i - 1]
end
end
len -= 1
end
p array
end

Test.bubble_sort_by(%w[hi hello hey]) do |left, right|
left.length - right.length
end









share|improve this question
















Can someone please show how to correctly format this yield statement, and why my methodology for this yield statement is incorrect? When run, the compiler results in an "undefined method 'length' error. "Test" is the main class.



  def bubble_sort_by(array)
len = array.length - 1
while len > 0
for i in(1..len)
@left = array[i]
@right = array[i - 1]
yield
if @left - @right > 0
array[i - 1], array[i] = array[i], array[i - 1]
end
end
len -= 1
end
p array
end

Test.bubble_sort_by(%w[hi hello hey]) do |left, right|
left.length - right.length
end






ruby-on-rails ruby yield






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 10:19









DonPaulie

919924




919924










asked Nov 25 '18 at 0:26









LawleyendaLawleyenda

359




359













  • If the block were { |a,b| a*b } and c = yield(2,3), a and b would be assigned values 2 and 3, respectively, so the block would return 6, which would be assigned to the variable c.

    – Cary Swoveland
    Nov 25 '18 at 0:34













  • Thank you for responding, Cary. @CarySwoveland how is " if yield(array[i-1], array[i]) > 1" not the same as the code written above for the if statement.

    – Lawleyenda
    Nov 25 '18 at 0:46













  • No, the body of the block (left.length - right.length) only has access to the variables directly passed to it by yield, not to any variables or methods that would be accessible within the method doing the yielding (bubble_sort_by).

    – Max
    Nov 25 '18 at 2:13



















  • If the block were { |a,b| a*b } and c = yield(2,3), a and b would be assigned values 2 and 3, respectively, so the block would return 6, which would be assigned to the variable c.

    – Cary Swoveland
    Nov 25 '18 at 0:34













  • Thank you for responding, Cary. @CarySwoveland how is " if yield(array[i-1], array[i]) > 1" not the same as the code written above for the if statement.

    – Lawleyenda
    Nov 25 '18 at 0:46













  • No, the body of the block (left.length - right.length) only has access to the variables directly passed to it by yield, not to any variables or methods that would be accessible within the method doing the yielding (bubble_sort_by).

    – Max
    Nov 25 '18 at 2:13

















If the block were { |a,b| a*b } and c = yield(2,3), a and b would be assigned values 2 and 3, respectively, so the block would return 6, which would be assigned to the variable c.

– Cary Swoveland
Nov 25 '18 at 0:34







If the block were { |a,b| a*b } and c = yield(2,3), a and b would be assigned values 2 and 3, respectively, so the block would return 6, which would be assigned to the variable c.

– Cary Swoveland
Nov 25 '18 at 0:34















Thank you for responding, Cary. @CarySwoveland how is " if yield(array[i-1], array[i]) > 1" not the same as the code written above for the if statement.

– Lawleyenda
Nov 25 '18 at 0:46







Thank you for responding, Cary. @CarySwoveland how is " if yield(array[i-1], array[i]) > 1" not the same as the code written above for the if statement.

– Lawleyenda
Nov 25 '18 at 0:46















No, the body of the block (left.length - right.length) only has access to the variables directly passed to it by yield, not to any variables or methods that would be accessible within the method doing the yielding (bubble_sort_by).

– Max
Nov 25 '18 at 2:13





No, the body of the block (left.length - right.length) only has access to the variables directly passed to it by yield, not to any variables or methods that would be accessible within the method doing the yielding (bubble_sort_by).

– Max
Nov 25 '18 at 2:13












2 Answers
2






active

oldest

votes


















2














because you need to pass arguments to yield.



try to change the line with yield into:
compared = yield @left, @right
and deal with the compared result






share|improve this answer































    2














    As I said in my comment on the question, yield needs to pass values for the block variables. Your code therefore needs to be modified as follows.



    def bubble_sort_by(array)
    len = array.length - 1
    while len > 0
    for i in(1..len)
    @left = array[i]
    @right = array[i - 1]
    if yield(@left, @right) > 0
    array[i - 1], array[i] = array[i], array[i - 1]
    end
    end
    len -= 1
    end
    array
    end

    bubble_sort_by(%w[hi hello hey]) do |left, right|
    left.length - right.length
    end
    #=> ["hello", "hey", "hi"]


    If, as here, the block being yielded to has block variables, the values of those variables must be passed as yield's arguments. The value computed by the block is then returned as though yield were the invocation of a method.



    If you prefer, you could replace the first line with



    def bubble_sort_by(array, &block)


    and replace if yield(@left, @right) > 0 with



    if block.call(@left, @right) > 0


    Here & converts the bloc to a Proc which is held by the variable block.






    share|improve this answer


























    • One small suggestion: would be nice to also explain what you changed and why is needed.

      – Rada Bogdan
      Nov 25 '18 at 8:20











    • @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

      – Cary Swoveland
      Nov 25 '18 at 8:24














    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%2f53463632%2fhow-yield-statement-in-ruby-works%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    because you need to pass arguments to yield.



    try to change the line with yield into:
    compared = yield @left, @right
    and deal with the compared result






    share|improve this answer




























      2














      because you need to pass arguments to yield.



      try to change the line with yield into:
      compared = yield @left, @right
      and deal with the compared result






      share|improve this answer


























        2












        2








        2







        because you need to pass arguments to yield.



        try to change the line with yield into:
        compared = yield @left, @right
        and deal with the compared result






        share|improve this answer













        because you need to pass arguments to yield.



        try to change the line with yield into:
        compared = yield @left, @right
        and deal with the compared result







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 1:05









        DonPaulieDonPaulie

        919924




        919924

























            2














            As I said in my comment on the question, yield needs to pass values for the block variables. Your code therefore needs to be modified as follows.



            def bubble_sort_by(array)
            len = array.length - 1
            while len > 0
            for i in(1..len)
            @left = array[i]
            @right = array[i - 1]
            if yield(@left, @right) > 0
            array[i - 1], array[i] = array[i], array[i - 1]
            end
            end
            len -= 1
            end
            array
            end

            bubble_sort_by(%w[hi hello hey]) do |left, right|
            left.length - right.length
            end
            #=> ["hello", "hey", "hi"]


            If, as here, the block being yielded to has block variables, the values of those variables must be passed as yield's arguments. The value computed by the block is then returned as though yield were the invocation of a method.



            If you prefer, you could replace the first line with



            def bubble_sort_by(array, &block)


            and replace if yield(@left, @right) > 0 with



            if block.call(@left, @right) > 0


            Here & converts the bloc to a Proc which is held by the variable block.






            share|improve this answer


























            • One small suggestion: would be nice to also explain what you changed and why is needed.

              – Rada Bogdan
              Nov 25 '18 at 8:20











            • @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

              – Cary Swoveland
              Nov 25 '18 at 8:24


















            2














            As I said in my comment on the question, yield needs to pass values for the block variables. Your code therefore needs to be modified as follows.



            def bubble_sort_by(array)
            len = array.length - 1
            while len > 0
            for i in(1..len)
            @left = array[i]
            @right = array[i - 1]
            if yield(@left, @right) > 0
            array[i - 1], array[i] = array[i], array[i - 1]
            end
            end
            len -= 1
            end
            array
            end

            bubble_sort_by(%w[hi hello hey]) do |left, right|
            left.length - right.length
            end
            #=> ["hello", "hey", "hi"]


            If, as here, the block being yielded to has block variables, the values of those variables must be passed as yield's arguments. The value computed by the block is then returned as though yield were the invocation of a method.



            If you prefer, you could replace the first line with



            def bubble_sort_by(array, &block)


            and replace if yield(@left, @right) > 0 with



            if block.call(@left, @right) > 0


            Here & converts the bloc to a Proc which is held by the variable block.






            share|improve this answer


























            • One small suggestion: would be nice to also explain what you changed and why is needed.

              – Rada Bogdan
              Nov 25 '18 at 8:20











            • @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

              – Cary Swoveland
              Nov 25 '18 at 8:24
















            2












            2








            2







            As I said in my comment on the question, yield needs to pass values for the block variables. Your code therefore needs to be modified as follows.



            def bubble_sort_by(array)
            len = array.length - 1
            while len > 0
            for i in(1..len)
            @left = array[i]
            @right = array[i - 1]
            if yield(@left, @right) > 0
            array[i - 1], array[i] = array[i], array[i - 1]
            end
            end
            len -= 1
            end
            array
            end

            bubble_sort_by(%w[hi hello hey]) do |left, right|
            left.length - right.length
            end
            #=> ["hello", "hey", "hi"]


            If, as here, the block being yielded to has block variables, the values of those variables must be passed as yield's arguments. The value computed by the block is then returned as though yield were the invocation of a method.



            If you prefer, you could replace the first line with



            def bubble_sort_by(array, &block)


            and replace if yield(@left, @right) > 0 with



            if block.call(@left, @right) > 0


            Here & converts the bloc to a Proc which is held by the variable block.






            share|improve this answer















            As I said in my comment on the question, yield needs to pass values for the block variables. Your code therefore needs to be modified as follows.



            def bubble_sort_by(array)
            len = array.length - 1
            while len > 0
            for i in(1..len)
            @left = array[i]
            @right = array[i - 1]
            if yield(@left, @right) > 0
            array[i - 1], array[i] = array[i], array[i - 1]
            end
            end
            len -= 1
            end
            array
            end

            bubble_sort_by(%w[hi hello hey]) do |left, right|
            left.length - right.length
            end
            #=> ["hello", "hey", "hi"]


            If, as here, the block being yielded to has block variables, the values of those variables must be passed as yield's arguments. The value computed by the block is then returned as though yield were the invocation of a method.



            If you prefer, you could replace the first line with



            def bubble_sort_by(array, &block)


            and replace if yield(@left, @right) > 0 with



            if block.call(@left, @right) > 0


            Here & converts the bloc to a Proc which is held by the variable block.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 25 '18 at 18:42

























            answered Nov 25 '18 at 1:52









            Cary SwovelandCary Swoveland

            71.5k54167




            71.5k54167













            • One small suggestion: would be nice to also explain what you changed and why is needed.

              – Rada Bogdan
              Nov 25 '18 at 8:20











            • @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

              – Cary Swoveland
              Nov 25 '18 at 8:24





















            • One small suggestion: would be nice to also explain what you changed and why is needed.

              – Rada Bogdan
              Nov 25 '18 at 8:20











            • @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

              – Cary Swoveland
              Nov 25 '18 at 8:24



















            One small suggestion: would be nice to also explain what you changed and why is needed.

            – Rada Bogdan
            Nov 25 '18 at 8:20





            One small suggestion: would be nice to also explain what you changed and why is needed.

            – Rada Bogdan
            Nov 25 '18 at 8:20













            @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

            – Cary Swoveland
            Nov 25 '18 at 8:24







            @Rada, that's a good point. The only reason I didn't elaborate was because I had eariler left an abbreviated explanation in a comment on the question. But you are right; I'll edit my answer.

            – Cary Swoveland
            Nov 25 '18 at 8:24




















            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%2f53463632%2fhow-yield-statement-in-ruby-works%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







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()