Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't ruby methods have lexical scope?

Tags:

closures

ruby

For example

def test
    a = "a is for apple"
    def inner_method
        a = "something" # this will refer to a different "a"
    end

    inner_method
    puts a
end

Are there any reasons for this? Blocks have lexical scope, so why don't methods? Is this going to be fixed?

like image 857
dpington Avatar asked Feb 01 '12 01:02

dpington


1 Answers

It's because Ruby's methods aren't first class objects (as they would be in IO, for example). So when you define the inner method, what is the receiver? Presumably the method itself, or the binding or something, but Ruby doesn't have that deep of OO.

Anyway, it's unclear to me what you were expecting to happen in your example, were you wanting it to modify the local variable a? If so, a proc is a suitable substitute for a method.

def test
  a = "a is for apple"
  inner_method = lambda do
    a = "something"
  end

  a # => "a is for apple"
  inner_method.call
  a # => "something"
end

test

"functional.rb" is a more extravagant example of this style of programming.

And "lambda, proc, and Proc.new" is a breakdown of Ruby's different types of closures.

like image 195
Joshua Cheek Avatar answered Nov 16 '22 18:11

Joshua Cheek