Frank Swarbrick
6/8/2006 2:51:00 AM
Andrew C. wrote:
> Hi, all.
>
> I'm a total newbie, currently working my way through 'Programming Ruby' by
> Dave Thomas et al. I've read a passage about the inheritance of local
> variables by blocks (p51 of my edition), and I can't quite make sense of
> it... or, rather, I thought I had a vague notion of what was being said, but
> I can't come up with any example code that demonstrates what I believe is
> being described.
>
> The passage says: "If the parameters to a block are existing local
> variables, those variables will be used as the block parameters, and their
> values may be changed by the block's execution... If [variables inside the
> block] first appeared outside the block, the variables will be shared
> between the block and the surrounding environment."
>
> Could someone show me a little code that demonstrates a block changing a
> pre-existing local variable, as all my experiments to do so either treat
> variables/parameters within the block as local or tells me they're
> undefined, so I guess I just don't understand.
>
> Thanks in advance for any assistance.
I've been puzzling over this as well. All I can think of is the
following example:
#!/usr/bin/env ruby
class Frank
def Frank.test(x)
yield 1, x
end
end
i = 0
Frank.test("Test") do |i, f|
puts i
puts f
end
puts i
puts f
With the results being:
1
Test
1
blocks.rb:15: undefined local variable or method `f' for main:Object
(NameError)
Since i was defined outside of the block prior to being passed as a
parameter to the block it can be changed (to a value of 1 in this case)
by the method to which the block was passed and will also exist once the
block has 'terminated'.
Since f was not defined outside of the block is no longer exists once
the block has terminated, thus the error on line 15.
If it refers to something else, well, ya got me...
Frank