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)