Explaining Ruby's Symbol object

What is a Symbol object?

A symbol is an object that has a one-to-one correspondence with any string. by official

How is it different from a character string?

First, create a symbol object by prefixing the string with a colon ":".

irb(main):001:0> :name
=> :name
irb(main):002:0> :name.class
=> Symbol

At first glance, it looks like a string, but ruby treats the symbol object as a ** integer **. This is a completely internal story, but unlike strings, symbols are processed as integers, so they are processed at high speed.

What is a good symbol?

For example, when a character string with the same contents is generated With a String object, even if the contents are the same, another object will be created. Symbol objects point to the same object, which saves memory.

Let's look at an example with String.

irb(main):014:0> string1 = 'String'
=> "String"
irb(main):015:0> string1.object_id
=> 180
irb(main):016:0> string2 = 'String'
=> "String"
irb(main):017:0> string2.object_id
=> 200

If you look at the object ID as an entity, they point to different things.

On the other hand, in symbol, if the contents are the same object, it points to the same object ID. In other words, it points to the same thing as an entity.

irb(main):021:0> symbol1 = :String
irb(main):021:0> symbol1 = :String
=> :String
irb(main):022:0> symbol1.object_id
=> 91428
irb(main):023:0> symbol2 = :String
=> :String
irb(main):024:0> symbol2.object_id
=> 91428

According to this specification, even if a new Symbol object is created, only one object is created. As a result, memory consumption can be reduced.

Usage of symbol

symbol is often used as the key for hash objects. (hash: an object that holds a key / value combination)

irb(main):025:0> { name: 'Masuyama', age: 29 }
=> {:name=>"Masuyama", :age=>29}

The hash example above has the value Masuyama for the key name and You can represent data with a value of 29 for a key of age.

In Ruby, the notation of adding a colon ":" to the key string is often used, but The key at this time will be treated as a symbol.

It is easy to understand if you imagine the column name of the database, Since the key itself is referenced from various data It's more efficient to use the same object than to create a new one each time data is created. That's why the symbol object is often used as the hash key.

Recommended Posts

Explaining Ruby's Symbol object
Explaining Ruby's Hash object
Explaining Ruby's Enumerator object