Search code examples
rubyyield

How to yield an argument


This method reproduces the map method in order to obtain a deeper understanding of how yield works.

I researched yield but I couldn't figure out why it is taking the iteration element as an argument.

I know yield retrieves a block, but what exactly is being yielded here and why does it take an argument?

The code below is correct:

def my_map(array)

  new_array = []
  array.each do |element|
    new_array << yield(element)
  end

  new_array
end

Solution

  • I tried to research yield a great deal but I can't figure out why in this case it is taking the iteration element as an argument.

    yield doesn't take an argument. The block does. yield yields the value to the block.

    I know yield retrieves a block,

    No, it yields control (and values) to the block.

    but what exactly is being yielded here and why does it take an argument?

    The object referenced by element is yielded to the block, along with the flow of control.