使用ERB打印数组的元素 [英] Printing elements of array using ERB

查看:89
本文介绍了使用ERB打印数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将控制器中定义的简单数组打印到视图中,并为每个元素添加新行.但是它正在做的是将整个数组打印在一行上.

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.

这是我的控制器:

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

这是我的观点:

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

结果如下:

<\br> <\br> <\br> <\br> ["Buy Milk", "Buy Soap", "Pay bill", "Draw Money"]

推荐答案

Erb(您在视图中使用的模板引擎)具有将红宝石代码嵌入模板的几种不同方式.

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

将代码放在<%= %>块中时,erb会在其中评估代码并在HTML中打印最后一条语句的值.由于ruby中的.each返回您迭代过的集合,因此使用<%= %>的循环将尝试打印整个数组的字符串表示形式.

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.

将代码放在<% %>块中时,erb只会评估代码,而不打印任何内容.这使您可以在视图中执行条件语句,循环或修改变量.

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.

您也可以从puts t中删除puts. Erb知道尝试将在<%= %>中看到的最后一个值转换为显示字符串.

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.

这篇关于使用ERB打印数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆