[MacRuby-devel] Bizarre behaviour with an instance variable

Eloy Durán eloy.de.enige at gmail.com
Thu Jan 27 05:46:59 PST 2011


I think you’re thinking about an unrelated change in 1.9, which is this:

% ruby -e 'x = 42; lambda { |x| x = 21 }.call(x); p x'
21
% ruby19 -e 'x = 42; lambda { |x| x = 21 }.call(x); p x'
42

In your example ‘theProjectRoot’ is not a parameter to the block, that's ‘f’. It could have been a local variable (or method) outside of the block, but that isn't so either, the one variable you defined that comes close is the instance variable named ‘@theProjectRoot’.

I hope this explains it better. If not feel free to ask more :)

On Jan 27, 2011, at 2:26 PM, Martin Hawkins wrote:

> Yes - a 1.9 change; 'parameters to a block are now always local to a
> block' - I'll probably forget again before it sticks.
> 
> On Jan 27, 9:44 am, Eloy Durán <eloy.de.en... at gmail.com> wrote:
>> The problem you are seeing is because inside the #map block you don't reference the project root variable as an instance variable, but as a local variable. Hence the error “undefined local variable or method `theProjectRoot'” :)
>> 
>> If you change the block like this, all should be good:
>> 
>>     map {|f| @theProjectRoot.stringByAppendingPathComponent(f) }
>> 
>> On Jan 27, 2011, at 10:18 AM, Martin Hawkins wrote:
>> 
>> 
>> 
>> 
>> 
>>> I find the following behaviour a little bizarre:
>>> At the macirb prompt (0.8)
>>> fileManager = NSFileManager.defaultManager
>>> @theProjectRoot = '/Users/martin/work/macruby/lots_of_files'
>>> => "/Users/martin/work/macruby/lots_of_files"
>>>>> filenames = fileManager.contentsOfDirectoryAtPath(@theProjectRoot, error:nil).map {|f| theProjectRoot.stringByAppendingPathComponent(f) }
>>> NameError: undefined local variable or method `theProjectRoot' for
>>> main:TopLevel
>> 
>>> If I create a local variable with the name theProjectRoot, then the
>>> statement runs correctly. According to the documentation,
>>> NSFileManager.defaultManager.contentsOfDirectoryAtPath requires a
>>> string; the scope of the variable should be irrelevant, shouldn't it?
>> 
>>> _______________________________________________
>>> MacRuby-devel mailing list
>>> MacRuby-de... at lists.macosforge.org
>>> http://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel
>> 
>> _______________________________________________
>> MacRuby-devel mailing list
>> MacRuby-de... at lists.macosforge.orghttp://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel
> _______________________________________________
> MacRuby-devel mailing list
> MacRuby-devel at lists.macosforge.org
> http://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel



More information about the MacRuby-devel mailing list