そのような単純な
c = :cat
c.to_s
puts c.class
シンボルをくれて、
c = "cat"
c.to_sym
puts c.class
文字列を与える. 私が使用している Ruby は 1.9.3 で、ドキュメントによると、シンボルを文字列に、文字列をシンボルに変換する必要があります。何が間違っている可能性がありますか?
to_s
元の変数を変更するのでto_sym
はなく、値を返します。.class
でチェーンで呼び出す必要があります.to_s
。
c = :cat
c.to_s.class
# "String"
c = "cat"
c.to_sym.class
# "Symbol"
新しい変数を変換したい場合は、それを割り当てる必要があります。
c = "cat"
d = c.to_sym
puts d.class
# d is a symbol
# "Symbol"
to_s
新しい値をto_sym
返しますが、変数は変換されません。
試す:
c = :cat
c = c.to_s
puts c.class # "String"
c = "cat"
c = c.to_sym
puts c.class # "Symbol"