4

I'm trying to understand how yield works in Ruby?

def ablock
i = 1
j = 2
yield(i, j, 3, 4)
end

ablock do |x| puts x
end

This gives me an output of - 1 2 3 4

But,

def ablock
i = 1
j = 2
yield(i, j, 3, 4)
end

ablock do |x,y| puts x, y
end

Gives me only 1 2 as the output. Why don't 3 & 4 print?

TheDareDevil
  • 129
  • 9

1 Answers1

3

The answer is pretty simple. You have defined your block method correctly but when you go to give it a code block you only give it one variable to hold 4 objects. Instead, try giving it a variable for each object you are yielding!

def ablock
    i=1
    j=2
    yield(i,j,3,4)
end

ablock do |i,j,k,l|
    puts i
    puts j
    puts k
    puts l
end

If you would only like to use one variable in your code block you have to do multiple yield statements(one for each object).

def ablock
  i=1
  j=2
  yield(i)
  yield(j)
  yield(3)
  yield(4)
end

ablock do |i|
  puts i
end

Happy coding!

Schylar
  • 774
  • 1
  • 5
  • 13