Object and symbol identifiers in Ruby

Object identifiers: Link to heading

In Ruby, each variable that is declared has a unique identifier (object_id) that refers to the object it contains. Even if two variables have the same content, their identifiers will be different.

Example: Link to heading

text = "Hello"
text_2 = "Hello"

text.object_id # => 1234567890 or something similar
text_2.object_id # => 9876543210 or something similar

# Although the content is the same, the IDs are different

Symbols: Link to heading

symbols are values ​​that do not change throughout the code. They are used to represent names of methods, variables, and other entities that do not need to be modified.

Example:

color = :red
color_2 = :red

color.object_id # => 1234567890
color_2.object_id # => 1234567890

# Variables with the same symbol share the same ID

Symbols have the same properties as normal variables: Link to heading

  • They can be used as keys in hashes.
  • They can be used as method arguments.
  • They can be compared with other symbols.

Convert a symbol to a string: Link to heading

:red.class # => Symbol

:red.to_s # => "red"

Advantages of using symbols: Link to heading

  • They are more memory efficient than strings.
  • They are faster to compare than chains.
  • They are easier to read and understand than strings.

When to use symbols: Link to heading

  • For names of methods, variables and other entities that do not change.
  • As keys in hashes.
  • As arguments to methods that expect a symbol name.

In summary: Link to heading

  • Object identifiers are unique for each variable, even if they have the same content.
  • Symbols are immutable values ​​used to represent names of methods, variables, and other entities.
  • Symbols are more memory efficient, faster to compare, and easier to read than strings.

Keep learning about object and symbol identifiers to take full advantage of Ruby!

<< Data types in Ruby Arrays in Ruby >>