Logo F2FInterview

Ruby Rails Interview Questions

Q   |   QA

Symbol are same like string but both behaviors is different based on object_id, memory and process time (cpu time) Strings are mutable , Symbols are immutable.

Mutable objects can be changed after assignment while immutable objects can only be overwritten. For example

p "string object jak".object_id #=> 22956070

p "string object jak".object_id #=> 22956030

p "string object jak".object_id #=> 22956090

 

p :symbol_object_jak.object_id #=> 247378

p :symbol_object_jak.object_id #=> 247378

p :symbol_object_jak.object_id #=> 247378

 

p " string object jak ".to_sym.object_id #=> 247518

p " string object jak ".to_sym.object_id #=> 247518

p " string object jak ".to_sym.object_id #=> 247518

 

p :symbol_object_jak.to_s.object_id #=> 22704460

p :symbol_object_jak.to_s.object_id #=> 22687010

p :symbol_object_jak.to_s.object_id #=> 21141310

 

And also it will differ by process time

For example:

Testing two symbol values for equality (or non-equality) is faster than testing two string values for equality,

Note : Each unique string value has an associated symbol

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: