What's the best way to use symbols?

Which is better?

1.

= link_to "Page", "/page", :class => "button", :data => {:theme => "green", :icon => "small-arrow"}

2.

= link_to "Page", "/page", class: "button", data: {theme: "green", icon: "small-arrow"}

3.

= link_to "Page", "/page", class: :button, data: {theme: :green, icon: "small-arrow"}

I found out that the symbols are the best way to use because of the memory alocation difference between symbols and strings.

I find version 2. as more readable (for me) and i think also more maintainable, because it's easier/faster to see/edit/add separated words (by space or dash) inside a string rather than edit a symbol and transform it to a string (when needed, like adding a second class "button login" or other theme "dark-red", for example).

Is there any serious reason (e.g. performance) to use the notation from 1. or 3. rather than 2.?

Answers


Note that it's not only about symbols, it's about old and new hash syntax.

I don't like to mix new hash syntax with symbols. New syntax looks well in most cases, for example:

{ width: 42, height: 24 }

But it looks horrible with symbols:

... class: :button ...

It is weird and not human readable, in my opinion. I dislike 3rd option. So, I prefer this option (you didn't mention it):

= link_to "Page", "/page", :class => :button, 
   :data => { :theme => :green, :icon => "small-arrow" }

This is better because :class symbol is written similar to :button symbol. Symbols should be written in the same syntax in a single line.


  1. Works in Ruby 1.8 as well as 1.9.

  2. Works only in 1.9. "button" and "green" aren't stored on the heap, and are mutable, however, they accurately convey that the value of them is what is important.

  3. Works only in 1.9. :button and :green are faster (marginally), at the expense of code that more poorly describes its intent.

In other words, 2 and 3 are the same in terms of the hash syntax. 1 and 2 are the same in terms of correct usage of strings vs symbols.


Need Your Help

Objects are not stored in NSMutableArray

nsmutablearray

I have a problem, storing instances of a viewController object. I want every user to have his/her own screen with some info on it and then be able to do modal to switch user.

Class of monads in Dart

class haskell dart monads

In Haskell, the definition of the class Monad is as follows: