Is there a way to covert a Symbol into a String?
For instance, a VariableMirror returns Symbols instead of Strings. Is there a way to convert a Symbol into a String, so I can print all the variable names of a class?
Strings can be changed, symbols cannot. In the above example, I was able to change the value of the str variable by concatenating a new string to it. When I tried to do this to the sym variable, I got an undefined method error message, because symbols are immutable!
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.
What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.
Symbol#to_sym() : to_sym() is a Symbol class method which returns the symbol representation of the symbol object. Syntax: Symbol.to_sym() Parameter: Symbol values. Return: the symbol representation of the symbol object.
Use MirrorSystem.getName():
import 'dart:mirrors';
void main() {
var sym = new Symbol('test');
print(MirrorSystem.getName(sym));
}
This outputs:
test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With