That is, we are talking about:
i = 100
x = 0
[1,2,3].each { |i| x += i }
I understand why it is incredibly helpful for x to refer to a variable in the enclosing scope (even if we could accomplish this same effect with a fold). What are the use cases for the parameter i referring to a variable in the enclosing scope?That's my second disappointment with Ruby blocks. The first was learning you could only have one block argument.
Do they resemble first-class objects at all? Can you assign a variable to a block? If you were to assign
{ |i| x += i }
to a variable outside that enclosing scope, and then used that variable in that scope, would i be overwritten in that call to the block?Do you mean one method can only have one block?
someObject.someMethod({block1},{block2}) def foo(x, y); x.call(y.call); end
foo(lambda {|x| 2+x}, lambda {1}) # => 3
It seems to me that in this case, the language degrades to approximately the same level as Common Lisp.Idiomatic Scheme basically never has "do" loops, despite their being part of the core standard, and it's been that way for decades.
y = {|x| x} # => #<Proc>
I agree that block syntax could therefore be greater than it is.I disagree that you can fairly knock Ruby for this, since blocks and implicit block arguments are still better than what you get in other languages.
irb(main):010:0> f = lambda { i = 100; x = 0; [1,2,3].each { |i| x += i }; x}
=> #<Proc:0x05011b34@(irb):10>
irb(main):011:0> f.call()
=> 6 macbook-pro-2:trunk raganwald$ ruby -v
=> ruby 1.8.6 (2007-03-13 patchlevel 0) [i686-darwin8.10.1]
macbook-pro-2:trunk raganwald$ irb
irb(main):001:0> lambda { i = 100; x = 0; [1,2,3].each { |i| x += i }; i }.call
=> 3http://weblog.raganwald.com/2007/02/why-ruby-is-not-acceptab...
Either ruby blocks create a new scope or they do not. Which is it?
Is there any way to specify if I want block-local or not?
The way python deals with scopes is to provide read access to outer scopes if there are no writes to a variable.
Edit: elided profanity.