Search code examples
rubyyieldblock

Problem with Ruby blocks


What is wrong in the code?

def call_block(n)

  if n==1

    return 0
  elsif n== 2

    return 1
  else
    yield
    return call_block(n-1) + call_block(n-2)

  end

end


puts call_block(10) {puts "Take this"}

I am trying to use yield to print Take this other than the tenth fibonacci number.

I am getting the error: in `call_block': no block given (LocalJumpError)

Even the following code throws error:

def call_block(n)

  if n==1
    yield
    return 0
  elsif n== 2
    yield
    return 1
  else
    yield
    return call_block(n-1) + call_block(n-2)

  end

end


puts call_block(10) {puts "Take this"}

Solution

  • You might want to use this line, as Adam Vandenberg hints:

    return call_block(n-1) { yield } + call_block(n-2) { yield }