Ruby - Module Symbol

Introduction

A symbol is an identifier whose first character is a colon :

:this is a symbol.

Symbol is not a string.

Symbol is not a constant, and it is not a variable.

A symbol is an identifier.

Ruby symbol is a name preceded by a colon, for example :description.

The Symbol class is defined in the Ruby class library to represent names inside the Ruby interpreter.

When you pass one or more symbols as arguments to attr_reader, which is a method of the Module class, Ruby creates an instance variable and a get accessor method.

This accessor method returns the value of the corresponding variable.

Both the instance variable and the accessor method will take the name that was specified by the symbol.

So, attr_reader( :description ) creates an instance variable with the name, @description, and an accessor method named description().

Symbols and Strings

A symbol is NOT a type of string.

Each string is different:

Demo

# These 3 strings have 3 different object_ids
puts( "hello".object_id ) 
puts( "hello".object_id ) 
puts( "hello".object_id )

Result

But a symbol is unique, so :hello, :hello, and :hello all refer to the same object with the same object_id.

Demo

# These 3 symbols have the same object_id
puts( :hello.object_id ) #=> 208712
puts( :hello.object_id ) #=> 208712
puts( :hello.object_id ) #=> 208712
# from  w  w  w  .j  a va 2  s  .  c om

Result

A symbol has more in common with an integer than with a string.

Each occurrence of integer value refers to the same object, so 10, 10, and 10 may be considered to be the same object.

They have the same object_id.

Demo

# These three symbols have the same object_id
puts( :ten.object_id )  #=> 20712
puts( :ten.object_id )  #=> 20712
puts( :ten.object_id )  #=> 20712
# w  w w .  jav  a 2 s .  co m
# These three integers have the same object_id
puts( 10.object_id )    #=> 21
puts( 10.object_id )    #=> 21
puts( 10.object_id )    #=> 21

Result

You can test for equality using the equal? method:

Demo

puts( :helloworld.equal?( :helloworld ) )     #=> true
puts( "helloworld".equal?( "helloworld" ) )   #=> false
puts( 1.equal?( 1 ) )                         #=> true
#   w w w  . ja v a  2s  .  c  o  m

Result

Related Topics