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

Paul Robinson paul at 32moves.com
Wed Sep 21 03:11:53 PDT 2011


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

> https://gist.github.com/1231642
> 
> 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. You can work around this by explicitly saying this.configuration or configuration(), but it certainly doesn't behave as you would expect.


I think line 9 should read:

@configuration = @configuration + 1

This makes it clear you mean the instance variable you have created with attr_accessor and you set the value of in initialize (incidentally with the instance variable syntax which might have given you a hint of what was going on). That should remove all ambiguity.

The syntax you've used - as others have said - will make Ruby think you mean to assign a value to a variable local to do_a_thing using the same variable which does not yet exist (but would do if the assignment could succeed), and will not do the "right and up" method call chain search that you might have expected.

Just as an aside, I read "Metaprogramming in Ruby" from Pragmatic Programmers a few months back, and found it one of the best explanations of how Ruby works (without having to sift through the source code) I've seen. I mention it because I think once you've read it (assuming you haven't already), not only will the answer to this query seem a little bit clearer, but you'll be able to pull off some seriously nice voodoo in Ruby. :-) Any other fans here?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20110921/8095923c/attachment.html>


More information about the Chat mailing list