tags:

views:

57

answers:

4

I'm trying to add a property called "enabled?" to a model with both a getter and a setter. However, when I do the following:

def enabled?= value
  # .. logic goes here ..
end

I get syntax error, unexpected '?', expecting '\n' or ';'

What should I be doing instead?

+3  A: 

A method name in ruby starts with a lower case letter or underscore optionally followed by upper and lower case letters underscores and digts. A method name may optionally end with a question mark, exclamation mark or equals sign.

So you can't!

You could follow the usual ruby idiom of defining enabled as follow :-

def enabled?
  @enabled
end

def enabled=(value)
  @enabled = value
end

To summarise. If you want to expose properties to the outside world then ensure your variable name will allow that within the confines of the rules for method names.

Steve Weet
A: 

Name your property just enabled

The query methods are just syntactic sugar, they are not mean to be used as properties or instance variables. You can add the method enabled? for syntactic sugar if you wish too.

Chubas
+6  A: 

Yes, ruby syntax only allows ? in method names if it's the last character, so foo?= is not valid. One thing you could do, that would be pretty idiomatic, is to define enabled?, enable and disable (or enable! and disable! if you want to emphasize that they're mutating methods).

If that doesn't fit your needs, you can just name the methods enabled? and enabled= and just live with the slight incosistency between the names.

sepp2k
Information on what exclamation marks usually mean are described in [Difference Between downcase and downcase! in Ruby](http://stackoverflow.com/questions/709229/difference-between-downcase-and-downcase-in-ruby/709271)
Andrew Grimm
A: 

I always name my boolean variables to start with 'is', as in 'isEnabled'. Then it has the same meaning as having the question mark w/o the need for complexity.

Shane N