Printing array elements using ERB

I am trying to print a simple array defined in my controller in my view with a new line for each element. But what he does is print the entire array on one line.

Here is my controller:

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

Here is my view:

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

Here is the result:

 <\br> <\br> <\br> <\br> ["Buy Milk", "Buy Soap", "Pay bill", "Draw Money"] 
+4
source share
5 answers

Erb, the template engine that you use in your views, has several different ways to embed ruby โ€‹โ€‹code inside templates.

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

When you put code inside the <% %> %% <% %> blocks, erb just evaluates the code, rather than printing anything. This allows you to execute conditional statements, loops, or change variables in a view.

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

+12
source

Two problems with your presentation:

  • you use "<% =" where you should use "<%".
  • you don't need "puts"

This should improve your results:

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

I would also consider using some HTML structure to better structure your todo list (instead of using the br tag at the end of lines), maybe not an ordered list:

 <ul> <% @todo_array.each do |t| %> <li><%= t %></li> <% end %> </ul> 
+5
source

Hey, why do you put the = sign on the first line. <%%> are used to indicate the rails that the line under this is a ruby โ€‹โ€‹code, evaluates it. Where as <% =%> this indicates to the rails that the line in these tags is in ruby, evaluates it and prints the result in the html file too.

So try checking your code you write

<%= @ todo_array.each do | t | %> while this line is only for iteration through @todo_array, so we will not print this line. So the final code should be

 <% @todo_array.each do |t| %> <%= puts t %> <% end %> 
+5
source

Just try:

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

instead

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

Remove the equal sign from each statement:

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

Source: https://habr.com/ru/post/1443955/


All Articles