From: Adam Shelly Date: 2008-08-29T02:36:18+09:00 Subject: Re: Writing a method to handle a code block? On 8/28/08, 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?). Yes the & is necessary, otherwise when you try to call this method with `each_vowel {|v|puts v}` you will get an argument error, since the method will expect a normal object, not a block. > What does it mean to have a method that takes a code block? At first approximation you can think of a code block as an anonymous method. You are writing a method that can take another method as an argument. > > %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). code_block.call(vowel) is calling the method stored in the code_block variable, and passing it the argument called vowel. When you call each_vowel like this: each_vowel {|vowel| puts vowel} The block with 'puts' is stored as code_block, and run 5 times, once for each letter in the array: %w{a e i o u}.each { |vowel| code_block.call(vowel) } So the end result is that each vowel is printed out. HTH, -Adam