At Symbol
The @
symbol is used to define instance variables (@ivar
) and class variables (@@cvar
). We'll also see it show up in the docs to differentiate unary operators from binary operators.
Instance and Class Variables
An instance variable is prefixed with @
and is unique to the instance of the object. A class variable is prefixed with @@
and is shared across all instances of the class.
Here is an only-sorta-contrived example of using instance and class variables:
class DatabaseConnection
@@active_connections = 0
@@max_connections = 100
def initialize(host, port)
@host = host
@port = port
@connected = false
end
def connect
if @@active_connections < @@max_connections
@connected = true
@@active_connections += 1
"Connected to #{@host}:#{@port}"
else
"Connection limit reached"
end
end
def disconnect
if @connected
@connected = false
@@active_connections -= 1
"Disconnected from #{@host}:#{@port}"
end
end
end
This class defines a couple class variables (@@active_connections
and @@max_connections
) at the top of its definition. It also defines a few instance variables (@host
, @port
, and @connected
) when an instance is initialized.
See the Ruby docs on instance variables ↗ and class variables ↗.
Unary Operator Documentation
The Integer
class, for instance, has two ways of using the -
operator. The one you might be familiar with is the binary operator for subtracting another number from the subject integer (note: two operands, hence binary operator). The Ruby docs show it as #-
(see Integer#-
↗). The -
operator can also be used as a unary operator for negating the subject integer (4
versus -4
). This is annotated in the Ruby docs as #-@
(see Integer#-@
↗).