Ruby on Rails: If Statements and an Introduction to Instance Variables
Checking if a condition is true can be very useful when creating web systems.
To show you an if statement works in RoR here is an code snippet that I recently used in a pages layout.
<% if @post.name %> <title><%= @post.category.name %> | <%= @post.name %></title> <% end %>
In this case all I do is set a different title if the post controlled page has a post name it can use for the title (for example if I was viewing the "show" post page).
I am not comparing values, I am simlpy checking if the post has a name. To check if a value exists, we can simply type it next to the if bit of the if statement. Note that I have an "@" sign when I'm looking at the things we described earlier, when in the "show" it would know the name of a post to put there; these are called instance variables.
Instance variables are basically variables, we can reffer to because they have a value (for example the "show" method knew the product name, because to show the product a product name must have been defined).
If you haven't already figured it out from my code snippet earlier, you start an if statement like this:
<% if CONDITION %>
and end it like this:
<% end %>
The code snippet earlier simply checked if the value was "true"; what if we wanted to actually check a value?
The following piece of code will show you how to, in this example check if the post's id is 2:
<% if post.id == 2 %>
We use the "==" because we are comparing the values, and not setting the id to 2.
There are also other comparison operators in RoR. Here is a list:
"==" Equal To
"<" Less Than
">" Greater Than
"<=" Less than or equal to
">=" Greater than or equal to
"!=" Does not equal
Just to show you how to use these, if you wanted to display an image if the post's id was not 2, you would do something like this:
<% if post.id != 2 %> <%= image_tag 'ImgName.jpg' %> <% end %>
Note that in this case I'm not using an instance variable, as this piece of code is designed to be in an "index" method (to be precise its in the bit were it goes through all the posts), in which you wouldn't use instance variables in this case.
Back to Ruby on Rails

