4

I just began digging into Ruby and Ruby on Rails, and I noticed two options for embedding Ruby syntax within .html.erb files:

<% #ruby code here %>

Or:

<%= #ruby code here %>

How should I choose one over the other?

Stuart Kershaw
  • 16,831
  • 6
  • 37
  • 48

2 Answers2

6

<%= outputs the result of the Ruby. <% just evaluates the Ruby.

<p>Hi! How are you? 1 + 1 = <%= 1 + 1 %></p>

Will become <p>Hi! How are you? 1 + 1 = 2</p>.

<p>Hi! How are you? 1 + 1 = <% 1 + 1 %></p>

Will become <p>Hi! How are you? 1 + 1 = </p>.

<% is generally used for flow control, ex. if/else. Example:

<% if model.nil? %>
  <%= render 'new_model_form' %>
<% else %>
  <%= render 'detail_view' %>
<% end %>

Read more at http://guides.rubyonrails.org/layouts_and_rendering.html

Zach Latta
  • 3,251
  • 5
  • 26
  • 40
1

<%= renders, <% does not.

Jim Pedid
  • 2,730
  • 3
  • 23
  • 27