This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: The "?" accessor debate
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Every now and then the Ruby community finds a small inconsistency in the language. Someone suggests a simple solution, and you smack yourself on the head and say, "Why haven't we been doing that all along?".
This came up because Nathaniel Talbott noticed that win32-service failed to build using the latest CVS Ruby. It turns out that they "patched" the Struct class not to allow "?" in struct members. This has come up before but wasn't resolved. Until now. And that broke my code. And that makes me angry.
The problem is that if you have a struct member with "foo?" there is no equivalent "foo?=" method. However, you can get away with it for a regular class:
class Foo
attr_accessor :foo?
end
If you were to do a "Foo.instance_methods", a "foo?=" method would show up on the list, even though that isn't valid syntax. Mathieu Bouchard proposed that we allow it. At first, I thought this was good idea. But Florian Gross made an excellent suggestion (in addition to pointing out that "?=" is just plain ugly). For "?" accessors, just create a "foo?" and "foo=", but no "foo?=". Brilliant!
However, Nathaniel then brought up this example:
class Foo
attr_accessor :foo?, :foo
end
What should happen here? I say that you end up with "foo", "foo?" and "foo=" methods. The second "foo=" would simply be overwritten. This is perfectly in line with current behavior, since you can declare the same accessor without so much as a warning from Ruby:
class Foo
attr_accessor :bar, :bar, :bar
attr_accessor :bar, :bar, :bar
end
This code is perfectly legal. Running with "-w -d" did not emit any warnings (which, perhaps, it should have).
Hopefully Matz will adopt Florian's suggestion, rather than just outlawing "?" in accessors, and thus Struct members. Florian's suggestion is more flexible and convenient all the way around as far as I can see. The only problem might be in implementation, since it means more checks on the backend.