Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 609
Veske Avatar asked Jan 31 '26 07:01

Veske


2 Answers

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 %>
like image 106
kddeisz Avatar answered Feb 01 '26 22:02

kddeisz


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).

like image 28
Simone Carletti Avatar answered Feb 01 '26 22:02

Simone Carletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!