Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby variable name with double underscores

Sometimes I see variable names with double underscore in the beginning and the end. For example:

Article.__elasticsearch__

Is there some naming convention related to double underscores in Ruby variable names?

like image 563
Иван Бишевац Avatar asked Apr 24 '14 13:04

Иван Бишевац


People also ask

Are underscores allowed in variable names?

Variable names should not start with underscore ( _ ) or dollar sign ( $ ) characters, even though both are allowed. This is in contrast to other coding conventions that state that underscores should be used to prefix all instance variables. Variable names should be short yet meaningful.

What does underscore mean in Ruby?

The first answer is on the level of the Ruby language: there is no use of the underscore in Ruby. It has no meaning. It is just a legal identifier like any other legal identifier. It could have been named foo or bar instead, and it would not in any way change the meaning of this code.

What are the naming conventions in Ruby?

General naming conventions in RubyClass names and module names use PascalCase. For example, ApplicationController. Method and variable names use snake_case. For example, attr_accessor.

Why we use underscore in variable names in C#?

The underscore before a variable name _val is nothing more than a convention. In C#, it is used when defining the private member variable for a public property.


2 Answers

An initial underscore or double underscore basically indicates "special/avoid overwrite" --meaning it's meant to reduce the likelihood that someone else might define a method/attribute of the same name. The most common occurrence is __send__.

From Ruby Forum

like image 118
Lenin Raj Rajasekaran Avatar answered Sep 16 '22 15:09

Lenin Raj Rajasekaran


The author of the ElasticSearch gem made the wrong call IMO. At the end of the thread, Avdi Grimm, who is well-known in the Ruby community, disagrees with the OP.

There's a reason you hadn't seen it yet and that it looks odd to you. It's because it's unidiomatic.

like image 20
Benjamin Atkin Avatar answered Sep 18 '22 15:09

Benjamin Atkin