开发者

How do I define a setter for a property whose name ends with a question mark?

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, u开发者_开发技巧nexpected '?', expecting '\n' or ';'

What should I be doing instead?


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.


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.


One small variation would be to alias the getter method, allowing both enabled and enabled?:

def enabled
  @enabled
end

def enabled=(value)
  @enabled = value
end

alias_method :enabled?, :enabled


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜