Reputation:
I have a segment of code:
<% @public_address.each do |key| %>
<%= key["address"]["address"] %>
<% end %>
This displays the keys properly, but this code
<% @public_address.each do |key| %>
<% puts key["address"]["address"] %>
<% end %>
displays nothing. What gives? What's the difference between the two?
Upvotes: 0
Views: 216
Reputation: 3080
The <% %>
and <%= %>
are used in erb to execute ruby code when rendering a template.
Erb is the default template engine in rails.
<% %>
Will evaluate the ruby code it contains, but "silently".
Meaning that no output is going to be printed on the rendered page.
<%= %>
on the other end, evaluates the ruby it contains and
renders the result on the rendered page.
What's the difference between <% code %> and <%= code %> in Rails erb?
Puts is simply a method from Ruby that is used to print a string at runtime. It has nothing to do with erb templates.
Upvotes: 1
Reputation: 1
In your first bit of code <%= key["address"]["address"] %>
, the <%= %>
is rails syntax for evaluating the code inside and returning the value.
In your second bit of code <% puts key["address"]["address"] %>
, you use <% %>
, which doesn't return an evaluated rails statement. Furthermore, puts is a method that outputs whatever follows it to the stout object. In a command line program, that means printing out to the terminal screen, but in a web app you aren't working with a terminal screen. You are working with controllers and view templates, so it is necessary to use the evaluative <%= %>
if you want to return values that will be displayed in the view.
Upvotes: 0