Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between a Symbol and String in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 264
    Comment on it

    A string is placed either within  single quotes i.e ('') or double quotes i.e ("") whereas on the other hand, a symbol is preceded by a colon i.e (:).

    A string has a variety of methods to use but contrary to that a symbol is like an isolated object.

    Due to the immutable nature of symbols, they are quite memory efficient because if we perform any operations on them then the original object is going to change thus its processing is done with celerity.

    Multiple symbols represents that a single value are identical i.e they refer to the same object whereas the same doesn't hold true for strings.

    For example:

    2.2.3 :001 > "demo".object_id
     => 17442620
    2.2.3 :002 > "demo".object_id
     => 17514260
    2.2.3 :003 > "demo".object_id
     => 17508220
    
    2.2.3 :004 > :demo.object_id
     => 1098588
    2.2.3 :005 > :demo.object_id
     => 1098588
    2.2.3 :006 > :demo.object_id
     => 1098588

    (object_id is a method inherited by String class from Object class).

    We generally use symbols like  hash keys where  unique identifier is needed, not a string.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: