Ofir Sasson
Ofir Sasson

Reputation: 671

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 %>

Upvotes: 1

Views: 1284

Answers (2)

hrnnvcnt
hrnnvcnt

Reputation: 944

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

Upvotes: 4

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

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

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

Upvotes: 3

Related Questions