On 03/20/2011 12:33 AM, Neubyr Neubyr wrote:
> Thanks for explaining it in detail Jeremy. That's helpful.
> 
> I had played with 'Array.each {block}' as most of the examples/book had 
> pointed out. But I couldn't understand how arguments are being passed to 
> blocks, so I started playing with some scalar variables (objects??). I 
> had referred to ri for some documentation, but didn't pay attention to 
> block-calls.
> 
> So a block is dependent on method preceding it, whose output gets passed 
> as args to block?? Sorry if that's really silly question.

No, think of a block as yet another argument to a method.  The value of
the method's result is not necessarily what is passed in.  It can be
anything that the method is written to pass in.  You might find that
writing a method that takes a block to be helpful:

def use_a_block
  yield(42)
end

use_a_block { |value| puts value }


The yield keyword calls the block given to the method and passes any
arguments given to the yield over to the block (in this case 42).  The
return value of the block becomes the return value of the yield keyword.
 The block acts sort of like an anonymous method that you can tell the
called method to use.

Here is a slightly more interesting example:

def use_a_block2(bool)
  if bool
    yield(42)
  else
    yield("hello")
  end

  "This is the return value of use_a_block2"
end

puts(use_a_block2(true) { |value| puts value })
puts(use_a_block2(false) { |value| puts value })


-Jeremy