简体   繁体   中英

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:

<%= @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?

The puts method is for printing a string to the console. 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 .

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.

Check the console and you will find, in the middle of the request logs, also the result of the puts statement.

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.logger.info "message"

Assuming it's just for debugging purpose, then it's fine to use puts (or p ).

it seems that the variable @print is the array. 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. You should put the loop in question in the view like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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