From: Josh Cheek Date: 2010-06-08T18:13:50+09:00 Subject: Re: Please explain this "Why's" example please --0016363b9b02e1692f04888134c1 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jun 8, 2010 at 1:07 AM, Kaye Ng wrote: > From Why's example: > _________________________________________________ > require 'wordlist' > > # Get evil idea and swap in code words > > print "Enter your new idea: " > > idea = gets > > code_words.each do |real, code| > idea.gsub!( real, code ) > end > __________________________________________________ > > Where is the beginning of 'end'? Is it 'require'? > (Like 'If' would be the beginning of an If statement (or is it block)) > > Thanks guys! > -- > Posted via http://www.ruby-forum.com/. > > The beginning is do. do ... end. This is called a code block. It is basically a method that you create in the middle of your code, as you need it. The method you are calling can in turn call your block to see how you want to handle some particular piece of code that should be custom to that one calling of the method. In your case, the method knows how to access each of the code words. But it doesn't know what you want to do with them. So you give it a block telling it what you want to do, and as it accesses the elements, it calls your block for each of them, passing them them into the block (your block says it is willing to receive them by placing "real" and "code" inside the pipes). In your case, the block looks through your idea and when it finds one of the real words, it replaces them with one of the code words. This brings up one of the important differences between blocks and methods, blocks can interact with the environment they are defined in. Methods cannot. On Tue, Jun 8, 2010 at 1:11 AM, Kaye Ng wrote: > Also, in Why's example, the words 'real' and 'code' are NOT variables, > correct? > Are they just random words that don't need to be defined? Like can I use > 'monkey' and 'ape' instead? > > Can you think of an easy way to find out? ^_^ --0016363b9b02e1692f04888134c1--