[Courses] [Ruby] Lesson 2: Containers, Blocks, and Iterators

Anne G anne at wjh.harvard.edu
Sun Dec 18 17:54:28 EST 2005


I have a hard time with the book. its song example
completely turns me off, it is much too wordy and too long
to be of any use to me, and it keeps poping out everywhere.

Here is an explanation of yield which works better for me

Think of a block as an anonymous subroutine. Instead of
saying
def func(x,y)
  # ... do stuff
end
it goes

{ |x,y|
  # ... do stuff

}

yield is just the way you call the block passed to the
function.  If you have a C/C++ background, it might help to
think of blocks as function pointers and yield as
dereferencing a function pointer.  Yield is similiar to a
callback function.  Even closer to function pointers in
C/C++ is a proc object.

myproc = proc { |x,y|
  puts "x: #{x}, y #{y}"

}

# You can accept these objects as parameters to functions
def func(x,y,p)
  p.call(x,y)
end

func(1,2,myproc)

Using yield is just a more convenient way to perform the
same thing.
The yield version of the above might go as follows:

def func(x,y)
  if( block_given?)
    yield(x,y)
  end
end

func(1,2) { |x,y|
  puts "x: #{x}, y #{y}"

}







More information about the Courses mailing list