[Ruby] What does 'yield' do in plain english?
Bob Marley
mlee1024 at gmail.com
Thu Jun 7 17:13:20 PDT 2007
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
More information about the Ruby
mailing list