John John -4 years ago 269
Ruby Question

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

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

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

def reverser
yield "hello"

reverser do |i|
puts i.reverse

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?

Answer Source

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

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

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

and that's it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download