What is the difference between string and symbol?

when should use string and symbol?

I think of a symbol as just a name - it’s not something to be divided up. A string is a sequence of bytes - you can extract words or characters from a string, etc.

There might be a performance difference in matching keywords vs strings, as a keyword is always the same object, whereas strings are different objects, even if they have the same contents.

See the object_id values here:

2.7.2 :010 > "abc".object_id
 => 200 
2.7.2 :011 > "abc".object_id
 => 220 
2.7.2 :012 > "abc".object_id
 => 240 
2.7.2 :013 > :abc.object_id
 => 2044828 
2.7.2 :014 > :abc.object_id
 => 2044828 
2.7.2 :015 > :abc.object_id
 => 2044828

I read somewhere that symbols for hash keys are more performant than strings.

It used to be (before 2.2) symbols were immutable and couldn’t be destroyed once instantiated.

Also, symbols use the same memory slot over and over again.

See this link

and this link for more details

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs