Why can't I access a local variable inside a method in Ruby?

ruby

Solution

The reason `ff` is inaccessible inside the `test` method definition is simply that methods (created with the `def` keyword) create a new scope. Same with defining classes and modules using the `class` and `module` keywords respectively.

The role of `main` (the top-level object) is almost completely irrelevant to the question of scope in this situation.

Note that, if you DO want your `test` method to have access to locals defined in the definition context, then use the `define_method` (or in your case, the `define_singleton_method` method), see here:

ff = "hi"
define_singleton_method("test") { ff }
test #=> "hi"

Unlike the `def` keyword, the `define_method` family of methods do not create new scopes but instead close over the current scope, capturing any local variables.

The reason using `@ff` worked in the next example given by @soup, is not that `main` is somehow a "special case" it's just that an ivar defined at top-level is an ivar of `main` and so is accessible to a method invoked on `main`.

What, however, is the relationship of the `test` method to `main`? It is not a method on just `main` itself - it is actually a private instance method defined on the `Object` class. This means that the `test` method would be available (as a private method) to nearly every object in your ruby program. All methods defined at top-level (`main`) are actually defined as private instance methods on the `Object` class.

For more information on the Ruby top-level, see this article: http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

Problem

I have a Ruby file named test.rb ``` ff="ff" def test puts ff end ``` I execute it, got error: `test.rb:3:in `test': undefined local variable or method `ff' for main:Object (NameError)` What's the reason for this? Is there any documentation to explain it?

Original source