Anders Strandl?v Elkj?r <ase / cs.auc.dk> writes:

> Hiyas. I am a bit puzzled about the use of 'do', 'begin' and
> 'end'. Why do you sometimes need the begin and other times
> not. Check the following code:

There are three kinds of grouping construct in Ruby:

1. Statements that contain multiple statements within them. These are
   things like if statements, for loops, and method and class
   definitions. These are always terminated with an 'end'

     class Fred
       def dave(a)
          if a == 1
            ...
          else
            ...
          end
       end
     end

2. As a special case of the above, 'begin' also heralds the start of a 
   group of statements, and also ends with an 'end'. begin/end
   constructs are most commonly used with exception handling:

      begin
        File.open(.,)
      rescue
        ...
      end

3. Finally (thankfully) there are code blocks. A code block is
   contained between braces { ... }, or between a 'do' and an 'end'
   (which is where most of the confusion arises.

   A code block may only appear after a method call, and has the
   effect of associating the code within the block with the call.

     each { |item|  puts item }

     each do |item|
       puts item
     end

   Why have both {} and do/end? Well, most of the time you can use
   them interchangeably. Underneath the covers, though, they have a
   different precedence, with '{}' binding more tightly to the left
   than do/end. You'll only notice this with your method call doesn't
   have parentheses around the parameter list. For example, given:

      def dave(a,b)
        for i in a..b
         yield i
        end
      end

   Then the following generates a syntax error,

      dave 1, 2 { |i| puts i }

   While

      dave 1, 2 do |i| puts i;  end

   works.


Regards


Dave