Parameter in a block is not local?

  • Thread starter SpringFlowers AutumnMoon
  • Start date
R

Rick DeNatale

Here's another example(a modification of the example found in pickaxe2,
p 106):

if false
data = "hello"
end

(1..3).each {data = "goodbye"}

puts data

--output:--
goodbye


That is equivalent to Java's call by value--but using references and C++
reference semantics, and the flat scope is converted to spheric scope
with assignment semantics applying throughout any call by value passing.

No it's not. no matter what 'spheric scope' means.

Blocks are closures, they are NOT functions/methods.

In the example the variable 'data' in the block is the same variable
as 'data' in data = 'hello'

In that sense this is no different than

if false; data = 'hello';end
data = 'goodbye'

The variable definition is lexical, so it doesn't matter that the
data='hello' statement didn't get executed, it's the fact that the
parser saw it which caused it to be defined.

And note that if you JUST had

1.times {a = "goodbye"}

with no prior definition of a in the scope, you'd get a NameError when
you ran it because a is undefined, and Ruby 1.8 doesn't allow new
locals to be defined within a block.

Ruby 1.9 has a feature marked EXPERIMENTAL which allows block locals
to be defined by listing them in the |'s preceded by a ; after any
block arguments. This might or might not survive.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,269
Messages
2,571,338
Members
48,025
Latest member
Rigor4

Latest Threads

Top