From: Chad Perrin Date: 2011-07-04T01:33:58+09:00 Subject: Re: symbol vs string for hash keys --1LKvkjL3sHcu1TtY Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Jul 04, 2011 at 12:28:03AM +0900, Intransition wrote: > What are the important factors to consider when deciding whether to > use symbols or strings for hash keys? >=20 > I ask b/c I noticed that fileutils.rb uses strings[1], though the keys > represent method names. Seems to me that symbols would be more > appropriate. >=20 > Even so it would be good to know the general criteria to consider. >=20 > [1]https://github.com/ruby/ruby/blob/trunk/lib/fileutils.rb > (OPT_TABLE) Strings are mutable; symbols are not. There is only one instance of any given literal symbol; there can be many instances of a given literal string. Basically, if it is more important to be able to operate on the names of your hash keys, strings are appropriate; if performance is more important, or you are sure no such operation on the names will be necessary, symbols are appropriate. It also makes sense to consider the fact that if you're selecting hash keys based on some kind of input, strings are easier -- because inputs tend to be strings rather than symbols, and would thus need to be translated into symbols if you use symbols as your hash keys. That's the ugly, hand-wavy, implementation-aware answer, I guess. The more conceptual answer is that symbols are identities and strings are data. I suspect strings are used in the example you provided because it is expected that when dealing with OPT_TABLE one might operate on a string in some manner before using it as a hash key. I'm really not sure, though. --=20 Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] --1LKvkjL3sHcu1TtY Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (FreeBSD) iEYEARECAAYFAk4QljkACgkQ9mn/Pj01uKWw9wCgyZqKKSe0lPd2V/z77/K1N6eJ HmIAoLycT9G038Uw08VoRWY0BR0+GdAg =cHbM -----END PGP SIGNATURE----- --1LKvkjL3sHcu1TtY--