[Ruby] What does 'yield' do in plain english?

Harry Dean Hudson Jr. dean at ero.com
Thu Jun 7 19:58:30 PDT 2007


On 6/7/07, Fruchterman, Thomas <tfrucht at amazon.com> wrote:
> Yield means "call the block that was passed into the function with the
> following arguments".

Another example that makes a lot of sense to me is Array#each. To
implement Array#each with a for loop you could do something like this:

irb(main):001:0> class Array
irb(main):002:1>   def new_each
irb(main):003:2>     for i in self
irb(main):004:3>       yield i
irb(main):005:3>     end
irb(main):006:2>   end
irb(main):007:1> end
=> nil
irb(main):008:0> f = [1,2,3]
=> [1, 2, 3]
irb(main):009:0> f.new_each {|i| puts i}
1
2
3
=> [1, 2, 3]

In this case new_each stepped through the array and called the given
block ({|i| puts i}) once for each element by yielding execution to
that block in the for loop (and passing it i).

Using it once makes sense because the behavior of the code calling
yield is dependent on the block of code that you pass it. The
degenerate example is:

def do_block
  yield
end

which just executes whatever block you pass it,

do_block {puts 'foo'}

will just puts "foo."

hope that helps,
dean.


More information about the Ruby mailing list