Search code examples
rubystringmethodsblockyield

Ruby default block and yield


I am working on the following problem:

describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

      expect(result).to eq("olleh")
    end

From my understanding this should reverse a string. My code is as follows:

def reverser
    yield "hello"
end

reverser do |i|
    puts i.reverse
end

This simply returns "hello". I may be missing some fundamental concepts here about how yield, blocks, and functions all interact. How do I going about doing what I am trying to accomplish?


Solution

  • The answers are good and correct but perhaps it still do not help.

    You should start with your spec:

    it "reverses the string returned by the default block"

    So, it's very clear what your method should do:

    def reverser
      # should reverse the string returned by the default block
    end
    

    Let's now see how to achieve it. Ok, it should reverse something. But what? Let's see:

    string returned by the default block

    This suggests that we need to execute the default block and get its returned value. Let's see what the docs say:

    yield - Called from inside a method body, yields control to the code block (if any) supplied as part of the method call. ... The value of a call to yield is the value of the executed code block.

    So, it seems that your method needs to perform a yield. It will execute a block and return the value the block returns. So, just put a yield there.

    def reverser
      yield
    end
    

    If you run your spec, it will complain - you will see that the string is still not reversed. So, that's whats left for your method to do:

    def reverser
      yield.reverse
    end
    

    and that's it.