From: Brian Candler Date: 2012-06-14T05:00:57+09:00 Subject: Re: Best practice of writing Rails code XPlay E. wrote in post #1064453: > I'm dealing with some issue about best practice of how to use Rails > code. Rails questions should be raised on a Rails mailing list, but the question you discuss is also just something about Ruby in general. > So, what's the best way to write the following lines that basicaly does > the same thing? > > Let's say we have a link that needs to be a button with some parameters > (theme, size and icon) > > 1. = link_to "Login", "#", class: "button", data: {theme: "green", size: > "large", icon: "small-arrow"} > vs. > 2. = link_to "Login", "#", class: :button, data: {theme: :green, size: > :large, icon: "small-arrow"} > > both of them should generate something like this > data-icon="small-arrow">Login The difference is that :button is a Symbol, whereas "button" is a String. There is a small performance difference: * Symbols are singleton objects. Whenever you use :button in your code, the same (immutable) object instance is returned. The symbol persists indefinitely. puts :foo.object_id puts :foo.object_id # same * Strings are mutable objects. The literal "button" returns a new object every time it is executed. Try this in irb: 10.times { puts "foo".object_id } So the symbol version is technically more efficient where the same symbol is being used over and over again. It is also quicker to test for equality (two Symbols are equal if their object_id is the same, you don't have to compare them character by character). For this reason they are often used as Hash keys. In practice, the difference in almost all real programs is negligible, so you should not get hung up over the performance issue. If you're talking Rails apps, almost certainly things like database accesses will be many orders of magnitude slower. As you have found, symbols which contain special characters need quoting anyway, so Symbol :"foo bar" is actually less convenient than String "foo bar" So use whatever feels best to you, i.e. makes you more productive as a programmer. Ten minutes of your development time saved is worth much more than 10 microseconds of runtime. -- Posted via http://www.ruby-forum.com/.