Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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 
like image 451
nonopolarity Avatar asked Mar 27 '11 11:03

nonopolarity


People also ask

Can method name and variable name be same?

Yes it's fine, mainly because, syntactically , they're used differently.

Can a variable with the same type and name be declared inside two different methods?

In a word, yes. Variable names only hold in the scope they're defined in, and you can use the same name in different scopes.

What is not allowed in a variable name?

Reserved keywords cannot be used as variable names. Reserved keywords are ALL, AND, BY, EQ, GE, GT, LE, LT, NE, NOT, OR, TO, and WITH. Variable names can be defined with any mixture of uppercase and lowercase characters, and case is preserved for display purposes.

Can a variable have the same name as a method in Java?

Yes, It is allowed to define a method with the same name as that of a class.


1 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.
like image 110
svoop Avatar answered Sep 21 '22 04:09

svoop