简体   繁体   English

使用推杆

[英]Using puts in rails

I have this code in controller: 我在控制器中有以下代码:

array = ["asd", "asd", "asd"]
    @print = array.each do |i|
       puts "Random text #{i}"
    end

And now I want to print it in some pages view like show.html.erb: 现在,我想在某些页面视图(例如show.html.erb)中打印它:

<%= @print >

And I get this: ["asd", "asd", "asd"] But In controller I sayd to puts each object in array, but it is not doing it? 而我得到这个: ["asd", "asd", "asd"]但是,在控制器我sayd到puts在阵列中的每个对象,但它没有这样做呢?

The puts method is for printing a string to the console. puts方法用于将字符串打印到控制台。 If you wanted to set each of the values of the array to a certain value in order to print it out later, you should use #map . 如果要将数组的每个值设置为某个值以便以后打印出来,则应使用#map

array = ['asd', 'asd', 'asd']
@print = array.map { |i| "Random text #{i}" }

Now, in your corresponding view, you should add: 现在,在相应的视图中,您应该添加:

<% @print.each do |val| %>
  <%= val %>
<% end %>

You should be doing the looping in your view. 您应该在视图中进行循环。 This helps maintain the separation between your application logic and your view code. 这有助于保持应用程序逻辑和视图代码之间的分离。

Controller 控制者

@array = ["asd", "asd", "asd"]

View 视图

<% @array.each do |i|
  <%= i %>    # No need to use the puts method here
<% end %>

puts prints to the stdout (standard output) that, in the majority of cases, corresponds to the console where you started the Rails server. 在大多数情况下, puts打印内容输出到标准输出(标准输出),该输出与启动Rails服务器的控制台相对应。

Check the console and you will find, in the middle of the request logs, also the result of the puts statement. 检查控制台,您将在请求日志的中间找到puts语句的结果。

A better way to print out something from the console is to use the Rails logger, especially if you want such output to be logged in the logs in production. 从控制台打印出某些内容的更好方法是使用Rails记录器,尤其是如果您希望将这样的输出记录在生产环境的日志中。

Rails.logger.info "message"

Assuming it's just for debugging purpose, then it's fine to use puts (or p ). 假设它仅用于调试目的,那么可以使用puts (或p )。

it seems that the variable @print is the array. 看来变量@print是数组。 The controller is run once per load of the page and then will output its contents at the end to the view. 该控制器在每次页面加载时运行一次,然后将其内容最后输出到视图。 Plus, "puts" is for printing a string to the console. 另外,“ puts”用于将字符串打印到控制台。 You should put the loop in question in the view like this: 您应该在如下视图中放入有问题的循环:

<% @array.each do |i| %>
  <%= i @>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM