Brian Ross wrote: > From Beginning Ruby: > > def each_vowel(&code_block) > %w{a e i o u}.each { |vowel| code_block.call(vowel) } > end > each_vowel { |vowel| puts vowel } > > I am trying to figure out how that works but I'm still having a bit of > trouble. Could someone break it down bit by bit to show what it's doing? > > def each_vowel(&code_block) > > It defines a method that takes a code block (is the & necessary?). What does > it mean to have a method that takes a code block? > > %w{a e i o u}.each { |vowel| code_block.call(vowel) } > > Then it takes an array of vowels, which call the each method to pass each > one into the following block through |vowel| as a block argument. The block > arguments are then called by the variable code_block (I don't understand > this). > > Brian > Code (in the form of Proc objects and similar) can be stored in a variable. >> code = proc { puts "test" } => #<Proc:0xb7b03030@(irb):25> >> code.call test => nil >> The &argument to each_vowel is a local variable that stores any block or closure passed to it using the special method() { syntax }. After that, calling argument.call is the same as code.call in the previous example. I got a little turned around in your question, either I'm just not understanding it or you're using a term wrong. The each method itself takes a block, the block is everything in the { curly braces }. The argument to the block is |vowel|, for every vowel in the array, the code block passed to each is called with that vowel passing it in |vowel|. That code block then goes an calls the code_block argument, which in turn contains the code block given when you called each_vowel. I can see how that explanation gets a little confusing. Two things are called vowel, there are three things called a "code block," and a few layers of calls through the code blocks. This example may be simpler. It duplicated the Fixnum#times method. >> def this_many_times(n,&block) >> n.times { block.call } >> end => nil >> this_many_times(10) { puts "test" } test test test test test test test test test test => 10 >> -- Michael Morin Guide to Ruby http://ruby.about.com/ Become an About.com Guide: beaguide.about.com About.com is part of the New York Times Company