Why can't a variable name end with `?` while a method name can?

A method name can end with a question mark ?

def has_completed?
  return count > 10
end

but a variable name cannot.

What is the reason for that? Isn't it convenient to have variable names ending the same way too? Given that we usually can't tell whether foobar is a method or a variable just by looking at the name foobar anyway, why the exception for the ? case?

And how should I work with this? Maybe always to use has or is in the code?

if process_has_completed
  ...
end

if user_is_using_console
  ...
end

Answers


You'd have to ask Matz to get an authoritative answer. However,

  • Ruby is an untyped programming language and a variable like finished? would imply a specific type (boolean) which appears somewhat contradictory to me.
  • A question somewhat requires a receiver (who can answer the question). A method must have a receiver (the object the method is called on), so a question mark makes sense. A variable on the other hand has no receiver, it's a mere container.

Now this is just a thought, but I think methods with names like empty? suggest that a some sort of check has to be made inside and object or a class (depending on the context). This check or evaluation means an action must be done. Overall, since we are asking (thus, ?) object for some state, means there is a possibility that object's state could change throughout the application's lifecycle. A variable could be outdated, but ?-method (check) will be done in the specific moment, thus providing an up-to-date information on some state that could be presented in a boolean form.

So I'd like to think that this is a design constraint provided by the architect (Matz) to enforce a more logical, close-to-real-life coding approach.


Need Your Help

When to use Path in WPF Binding?

wpf xaml data-binding

I've seen a lot of WPF Binding examples and have used the feature in a lot of different places in learning MVVM, but something that has seemed quite inconsistent to me is when you specify "Path=" i...

How do I pause Flash content in an Android WebView when my activity isn't visible?

android android-webview android-2.2-froyo

I am experimenting with using a WebView to display Flash content inside my activity. Everything is working pretty well, but when the user hits the home key to put the activity into the background, ...