“Chad P.” [email protected] wrote in message
news:[email protected]…
sub foo {
I’m hoping that demonstrating how it does or does not work in Perl will
make it clear what I’m talking about, based on similar syntax between
the languages, so that I can find out what does and does not work in
Ruby. Duh?
Well, I suppose the question can be directed only to those who know
Perl
but the two languages seem to be sufficiently different (despite Ruby’s
Perl
origins) that your analogies are hard to make or make clear…
within them go out of scope while the block is still in scope, I’d like
to know. If there’s some other way to “close” the block’s data while
the block is still available, I’d like to know that, too.
I'm having trouble parsing your sentences here so I am going to
pretend
that I understand you and you can tell me where I’m going wrong, okay?
These are Ruby blocks:
[1, 2, 3].each do |i|
# this is a Ruby block and
# this is a closure
end
So explain how it is a closure. Please.
Okay, I think I can do this much...
I'm going to implement the "each" method of an array using the
passed in
block, which is a closure, using the array reference operator “[]” and
the
size method…
local_variable = 2
class Array
# local_variable is outside this scope…
def each
# local_variable is also outside this scope...
i = 0
while i < self.size
# call the passed in block which is also a closure...
yeild self[i]
i += 1
end
end
end
array = [1, 2, 3]
array.each do |i|
# we have access to local_variable even though this
# will be executed far away from local_variable’s scope
# because this block of code is a closure…
puts local_variable * i
end
some_local_variable = 2
func = lambda { puts some_local_variable } # a one line block and
closure
Am I to assume that some_local_variable is going out of scope outside of
the lambda declaration at some point, to create that closure?
Yes, you are. It didn't occur to me to demonstrate that it was a
closure, only how to make blocks that are closures in Ruby. I hope the
previous paragraph demonstrated what you wanted to know…
All things that are called "blocks" in Ruby are closures.
Do you still have any questions on the matter?
Yes. Are you just failing to explain how these things are closures, or
do you not know what a closure is? You keep telling me blocks are
closures somehow, but you’re not explaining how. Saying it doesn’t make
it so. Please explain what I’m missing.
I _think_ I know what a closure is, as long as Wikipedia and all
Ruby
tutorials haven’t conspired to lie to me. Again, it didn’t occur to me
show
you that they are closures. I was only trying to show you what will
make a
closure…
So, are these closures, as you understand them? How is your
understanding different from mine?