Translate

February 5, 2014

What is the difference between Symbol and String in Ruby?

The symbol in Ruby on rails act the same way as the string but the difference is in their behaviors that are opposite to each other.

The difference remains in the object_id, memory and process time for both of them when used together at one time.

Strings are considered as mutable objects. Whereas, symbols, belongs to the category of immutable.

Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten.

String objects are written like
irb(main):001:0> "string object apple".object_id #=>70278982314860
or
irb(main):002:0> "string object
apple".to_sym.object_id #=> 456148

Symbols are used to show the values for the actions like equality or non-equality to test the symbols faster then the string values.
Post a Comment