Ruby on Rails- :symbols, @iVars and "strings" - oh my!

Meltemi picture Meltemi · Jun 8, 2010 · Viewed 19.1k times · Source

New to Rails and trying to get my head around when/why to use :symbols, @ivars , "strings" within the framework.

I think I understand the differences between them conceptually

  • only one :symbol instance per project
  • one @ivar per instance
  • multiple "strings" - as they are created whenever referenced (?)

Feel free to correct me!

The main confusion comes from understanding the rules & conventions of what Rails expects - where and WHY?

I'm sure there's an "Ah ha!" moment coming but I haven't had it yet...as it seems pretty arbitrary to me (coming from C/Obj-C).

-thx

Answer

Pran picture Pran · Jun 8, 2010

The @instance_variable is an instance variable. It is usually defined in the controller and accessible in the views.

The "string" is a string, like as in any other language.

The :symbol, is as you mentioned it's an efficient way of representing names and strings; they are literal values. It is initialized and exists only once during the ruby session. It's not a string, since you don't have access to String methods; it's a Symbol. On top of that, it's immutable. For those reasons, it becomes very handy in representing keys in hashs. Rails methods uses hashes, thus, you find symbols a bit everywhere in Rails.