Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Converting string to symbol & symbol to string in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 7.62k
    Comment on it

    Ruby supports both Strings & Symbols.
    String being mutable & Symbols being immutable cater to different needs.

    We can convert String to Symbol & Symbol to String at any time.

    To convert a string to a symbol, we can use intern method or to_sym method which are aliases to each other.

    ex:- (using intern method)

    >> a = "taran"
    => "taran"
    >> a.class
    => String
    >> b = a.intern
    => :taran
    >> b.class
    => Symbol
    

    (using to_sym method)

    >> a = "taran"
    => "taran"
    >> a.class
    => String
    >> b = a.to_sym
    => :taran
    >> b.class
    => Symbol
    


    To convert a Symbol to a String we can use the to_s method

    >> b = :car
    => :car
    >> b.class
    => Symbol
    >> a = b.to_s
    => "car"
    >> a.class
    => 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: