很多新手可能不能很好地理解 ruby 下的 Symbols 与 String 的差异,感谢@chenzhong 分享的一篇文章,供大家参考参考,原文地址,猛戳这里
文章最后的结论:
to use strings when:
you want to use any of string methods like #upcase, #split, #downcase etc.
you want to change/mutate the string
to use Symbols when:
symbols can't be changed at runtime. If you need something that absolutely, positively must remain constant
Places where same string is going to be repeatably used, example hash keys are pretty good candidate for symbols. so instead of string keys,hash["key"] = value. you should use symbols like this hash[:key] = value
To conclude, strings & symbols in ruby are similar but differences given above. But the main difference is that symbols are immutable & slightly more performant than strings so you should you them place where you know same string is likely to be repeated again & again.