Reputation: 61
I am learning about named constructors in Rails, and for the exercise we have to try to find the class hierarchy for a symbol. First, I have to create a symbol using a named constructor. I have tried both
s = Symbol.new(:newsymbol)
and
s = Symbol.new(:"newsymbol")
but both are telling me that "new" is an undefined method for the Symbol class. Is there something with the symbol class that doesn't allow the "new" method to be applied to it, or am I using an incorrect literal constructor for symbol?
Upvotes: 0
Views: 260
Reputation: 1912
In you examples
s = Symbol.new(:new_symbol)
which won't run is equivalent to the following which does run
s = :new_symbol # :new_symbol is already a symbol!
Now there IS a method that turns a string into a symbol:
s = "new_symbol".to_sym
which sets s
with the value :new_symbol
. Perhaps that was what you had in mind?
Upvotes: 0
Reputation: 1374
The Symbol class in Ruby doesn't have the Symbol#new method. This has to do with symbols being unique. To use the literal you would just use the leading semicolon. Here are a few examples:
s = :s
s = :cat
s = :"A symbol with spaces in it"
Upvotes: 2