简体   繁体   中英

Ruby on Rails: Print element of array in a single line in html.erb file

I'm new to html.erb files and I didn't find an answer to my problem. I have array of names and I'm trying to print them in a paragraph tag <p> in one line with ',' like that:

name1, name2, name3

But instead I get this:

name1,
name2,

This is the code:

<% @names_array.each do |name| %>
  <p class="center"><%= name %>,</p>
<% end %>

You can use Active Support's to_sentence method. Example:

names = ['name1', 'name2', 'name3']

irb(main):001:0> names = ['name1', 'name2', 'name3']
=> ["name1", "name2", "name3"]

irb(main):002:0> names.to_sentence
=> "name1, name2 and name3"

You can modify the last connector passing a word option:

irb(main):003:0> names.to_sentence(last_word_connector: ', ')
=> "name1, name2, name3"

Check the documentation

Doesn't something like this work?, just join them, leaving them inside the paragraph tag:

<p class="center">
  <%= @names_array.join(', ') %>
</p>

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