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

Fruchterman, Thomas tfrucht at amazon.com
Thu Jun 7 19:44:32 PDT 2007


Yield means "call the block that was passed into the function with the
following arguments".

When you can a function like this: 

 fibUpTo(1000) { |f| print f, " " }

the block is that funny thing that looks like code between {} or do end.
Doesn't that |f| sort of look like an argument list? In this case, the
function fibUpTo is being called with 2 arguments, 1000 and { |f| print
f, " " }. You can just pretend that the block is a function named yield
that you are calling from with fibUpTo.

Why do we do it? It's incredibly useful to be able to call a function
with code that can vary as well as data.



-----Original Message-----
From: ruby-bounces at zenspider.com [mailto:ruby-bounces at zenspider.com] On
Behalf Of Bob Marley
Sent: Thursday, June 07, 2007 5:13 PM
To: ruby at zenspider.com
Subject: [Ruby] What does 'yield' do in plain english?

Hello,

I am trying to follow some code that uses the keyword 'yield' but I am
getting confused what this keyword is actually doing:

require 'rubygems'
require 'mysql'

def with_db
    dbh = Mysql.real_connect('localhost', 'root', '',
'buildwatch_development')

    begin
        yield   dbh
    ensure
        dbh.close
    end
end

with_db do |db|
    res = db.query('select id, status, build_url from watches')
    res.each{|row| puts "#{row[0]} : #{row[1]} : #{row[2]}"}
    res.free
end

The explanation for yield from the programming ruby book 1st ed, for me
was equally confusing:

def fibUpTo(max)
  i1, i2 = 1, 1        # parallel assignment
  while i1 <= max
    yield i1
    i1, i2 = i2, i1+i2
  end
end
fibUpTo(1000) { |f| print f, " " }


I can kind of follow from the simple example:
def threeTimes
  yield
  yield
  yield
end

threeTimes { puts "Hello" }

My concept of yield is off as I interpret it as a kind of substitution,
ie the def threeTimes example. But in the first two example if you're
going to use the yield once, why bother?

Kinda lost,

miene
_______________________________________________
Ruby at zenspider.com - Seattle.rb non-commercial list
http://www.zenspider.com/seattle.rb
http://www.zenspider.com/mailman/listinfo/ruby


More information about the Ruby mailing list