user2544124
user2544124

Reputation:

What is the difference between <%= and the "puts" command in rails?

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

Answers (2)

Marc Lainez
Marc Lainez

Reputation: 3080

The <% %> and <%= %> are used in erb to execute ruby code when rendering a template.

Erb is the default template engine in rails.

Difference between <% %> and <%= %>

  1. <% %> Will evaluate the ruby code it contains, but "silently". Meaning that no output is going to be printed on the rendered page.

  2. <%= %> 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?

What's puts?

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

Mike Vezzani
Mike Vezzani

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

Related Questions