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

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


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.


Instance variables are pretty straightforward: they track properties/values of a particular instance, so you use them when you the values will vary across instances.

Symbols vs. strings are a bit more arbitrary. Symbols are generally used for constant values, in much the same way that a language such as C would use enums; Ruby doesn't have enums, so symbols are often used to fill that gap. Strings are used for more varied pieces of text that won't be used as a flag or similar constant.


Symbols are kind of like pointers (not in the C-ish way, but in C-ish thinking, they point). Well, you use symbols when you are manipulating properties. They are one of the great benefits of dynamic typing if you'd ask me. (For potential voters I do not mean any harm, I do know that they are not pointers, but it felt 'ah-ha!' for me).

:action => "index"

Instance variables are needed when you fetch data from your model and you want to use them across your views (inside your controller method).

def my_controller_method@myposts = Post.find(:all)end# inside view<% for @myposts do |m| %><i><%= m.title %></i><% end %>

Just a heads up, the rules and conventions kinda change rapidly (as I discovered on my Rails journey) quite a lot per version. Having the right guide with the right Rails helps. Good luck with coding!