From: Dave Grijalva Date: 2007-05-30T08:06:58+09:00 Subject: Re: Symbols vs. Strings ------=_Part_204386_12296772.1180480018920 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline I think the second point that Emilio was making is the more important one. Let me try to clarify: irb(main):008:0> puts "foo".object_id 1724824 => nil irb(main):009:0> puts "foo".object_id 1708744 => nil irb(main):010:0> puts :foo.object_id 3678478 => nil irb(main):011:0> puts :foo.object_id 3678478 You can see here that a new String object is created every time you use a literal string. With a symbol, however, you are re-using the same object anywhere you use a symbol with the same name. Using symbols can save you a lot of resources, both processor time and memory. -dave On 5/29/07, Emilio Tagua wrote: > > On 5/29/07, John Blanco wrote: > > I'm new to Ruby, but coming up to speed quickly. One question I still > > have never seen a good explanation to is this: When is it preferred to a > > key a hash with a symbol, and when is it keyed by string? Is this just > > personal preference, or is there a rule of thumb? > > > > For example, in the Rails book, the session variable is always populated > > with symbols, i.e.: > > > > session[:user] = User.new > > > > It's also obviously completely common throughout the Rails framework > > (e.g., :controller =>, :action =>, etc.) > > > > So, when should I use what...or what should I prefer? > > Symbols are ligh-weight, they don't have so much methods to initialize > has strings: > > irb(main):009:0> :asd.methods.size > => 45 > irb(main):010:0> "asd".methods.size > => 143 > > So thats why you use it in params or other places when you just need > the name. Also a difference is that a symbol :sym is :sym everywhere, > but a string "string" -only the string, not assigned to a variable- is > a different refence to a String object each time you write "string" . > > Those are the most important diferences IMO. Sorry if i wasn't that clear > tho. > > Cheers > > ------=_Part_204386_12296772.1180480018920--