[LRUG] attr_accessor parsed as a method variable when setting with a get

Graham Ashton graham at effectif.com
Wed Sep 21 02:59:04 PDT 2011


On 21 Sep 2011, at 10:50, James Darling wrote:

> I spent quite a while trying to isolate an issue yesterday. I've done so now, and worked around it, but now I'm interested in what's going on.

  def do_a_thing
    configuration = configuration + 1
  end

If you've got a method on self called configuration, assignment like this poses a problem for Ruby. There's no hint whether you meant to create a local variable called configuration (which is actually what the code says), or call the method.

It therefore assumes you're assigning to a local variable.

> It seems that on line 9, the second use of the configuration getter method call is being parsed as a method variable, which is nil as it isn't set.

The configuration variable needs to refer to the same object wherever you refer to it within this scope, and it therefore both variables have to be local to the method.

> Anyone come across this before? Any ideas why it happens? Is it fixable, or just an unfortunate byproduct of how ruby parses?

Yep, it cost me an hour of debugging a couple of years ago, after which point it's never managed to bite me again.

`self.configuration =` will sort it.


More information about the Chat mailing list