From: Brian Candler Date: 2002-11-14T19:16:51+09:00 Subject: Re: Newbie Question. On Thu, Nov 14, 2002 at 01:29:51AM +0900, montana wrote: > Simple Newbie question. I kind of understand this whole block thing. > > 3.times {|i| puts i} > > Bassically this is similar to > > a for statement in other languages. > > What throws me off is the > > something do |line| > #process something and line here > end > > Is this correct? You take some object named something and process it's values in the do-end statement using the variable list?? The curly brackets and do..end are actually identical (apart from their precedence when being parsed). So you can write either: 3.times {|i| puts i} or 3.times do |i| puts i end In both cases, you are calling method "times" of the number 3, and passing a block of code. The number 3 executes this code block 3 times. On each iteration it replaces |i| with the index value, from 0 to 2. [Note that although irb shows "0 1 2 3", the loop is only executed three times with indexes of 0 to 2. 3 is the final value returned by the expression, and irb prints it] The idea of a number doing work for you might seem like a strange way of doing things, but it gets clearer when you ask an Array to execute some code for each of its elements: a=["hello","to","you"] a.each {|i| puts i} Other objects respond to 'each', including Range, which gives you something closer to a for loop: (1..10).each {|i| puts i} For a good explanation see http://165.193.123.250/book/tut_containers.html (that's www.rubycentral.com but its DNS is broken) Regards, Brian.