[Newbies] A question about returning values from a block

Randal L. Schwartz merlyn at stonehenge.com
Wed Dec 30 23:58:08 UTC 2009


An explicit "answer" from a block exits the method in which the
block is defined.  This is often used for "easy answers" in a method:

someMethodFor: aValue

  aValue < 3 ifTrue: [^7].
  aValue > 10 ifTrue: [^aValue * 10].
  ^aValue complexExpressionHere.

As you discovered, if you don't answer from a block, the block's value is the
last expression evaluated.

You actually *can* return a value from the "middle" of a block, but at that
point, the code within the block is better factored out as a separate method.
In fact, nested blocks and complex blocks and desire to have complex control
inside a block are all signs that you aren't yet thinking in terms of small,
single-purpose methods.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion


More information about the Beginners mailing list