Robert D. wrote:
Anyway, I will tell you what is important to me:
Blocks in Ruby are Proc objects, always, can you agree with this
statement,
No, it doesnât seem to me that they are. As I said before, in Ruby a
block does not, by default, have its own independent existence. Let me
illustrate by comparison with Smalltalk. When we write blocks and use
them with methods (e.g. times in Ruby or timesRepeat: in Smalltalk) they
may appear to be more or less the same:
- SMALLTALK
i := 0.
10 timesRepeat: [ i := i + 1 ].
i.
- RUBY
i = 0
10.times{ i += 1 }
puts( i )
BUT, a Smalltalk Block can be its own object. It is not obliged to be
used with some âblock-awareâ method. Compare the following:
- SMALLTALK
i := 0.
myBlock := [ i := i + 1 ].
10 timesRepeat: myBlock.
- RUBY (a)
i = 0
myBlock = { i += 1 } # <= error: Ruby thinks this is a hash
10.times{ i += 1 }
puts( i )
- RUBY (b)
i = 0
myBlock = { || i += 1 } # <= syntax error
10.times{ i += 1 }
puts( i )
- RUBY (c)
i = 0
myBlock = proc{ i += 1 } #<= Hurrah! Works by explictly âconvertingâ to
Proc
10.times{ i += 1 }
puts( i )
In Smalltalk, a block is always an instance of its class. e.g.
myBlock := [ i := i + 1 ].
myBlock class.
âŚSmalltalk replies: BlockClosure.
Itâs a subtle point, I know, and I donât want to make any big deal of
it. After all, when a Proc object block is explicitly created from a
Ruby block, it works in a comparable way to a Smalltalk block. However,
that doesnât alter the fact that, in Ruby, blocks (chunks of code
delimited by {âŚ} or doâŚend) are not normally instances of the Proc
class. They are, well, just chuncks of code but not objects. To
demonstrate that, try evaluating a block:
-
SMALLTALK
[ i := i + 1 ] class.
âŚAnswers: BlockClosure
-
RUBY
{ i += 1 }.class
âŚAnswers: syntax error, unexpected â}â, expecting $end { || i += 1
}.class
do i += 1 end.class
âŚAnwsers: syntax error, unexpected kEND, expecting $end do i += 1
end.class
best wishes
Huw
SapphireSteel Software
Ruby and Rails In Visual Studio
http://www.sapphiresteel.com