5

I'm trying to print a simple array defined in my controller into my view with a new line for each element. But what it's doing is printing the whole array on one line.

Here's my controller:

class TodosController < ApplicationController
  def index
    @todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]
  end
end

Here's my view:

<%= @todo_array.each do |t| %>
<%= puts t %><\br>
<% end %>

Here's the result:

<\br> <\br> <\br> <\br> ["Buy Milk", "Buy Soap", "Pay bill", "Draw Money"]
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Keva161
  • 2,623
  • 9
  • 44
  • 68

5 Answers5

14

Erb, the templating engine you're using in your views, has a few different ways of embedding ruby code inside templates.

When you put code inside <%= %> blocks, erb evaluates the code inside and prints the value of the last statement in the HTML. Since .each in ruby returns the collection you iterated over, the loop using <%= %> attempts to print a string representation of the entire array.

When you put code inside <% %> blocks, erb just evaluates the code, not printing anything. This allows you to do conditional statements, loops, or modify variables in the view.

You can also remove the puts from puts t. Erb knows to try to convert the last value it saw inside <%= %> into a string for display.

spike
  • 9,794
  • 9
  • 54
  • 85
7

Just try:

<%= @todo_array.join('<br />').html_safe %>

instead of

<%= @todo_array.each do |t| %>
   <%= puts t %><\br>
<% end %>
RAJ
  • 9,697
  • 1
  • 33
  • 63
6

Hey why are you putting '=' sign in first line. <% %> are used for telling rails that string under this is ruby code,evaluate it. Where as <%= %> this tells rails that string in these tags is in ruby, evaluate it and print the result in html file too.

Hence try to inspect your code you are writing

<%= @todo_array.each do |t| %> while this line is only for iterating over @todo_array hence we wont be in need to print that line. So final code should be

<% @todo_array.each do |t| %>
 <%= puts t %>
<% end %>
Akshay Vishnoi
  • 1,252
  • 12
  • 15
5

Two issues with your view:

  1. you are using "<%=" where you should be using "<%".
  2. you don't need 'puts'

This should improve your results:

<% @todo_array.each do |t| %>
  <%= t %><\br>
<% end %>

I would further consider using some HTML structure to better structure your todo list (instead of using br tag at the end of lines), perhaps an un-ordered list like so:

<ul>
  <% @todo_array.each do |t| %>
    <li><%= t %></li>
  <% end %>
</ul>
SporkInventor
  • 3,120
  • 2
  • 16
  • 11
2

Remove the equal sign from your each statement:

<% @todo_array.each do |t| %>
  <%= t %><\br>
<% end %>
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64